package weaver.docs.docs;

import com.api.doc.detail.service.DocSaveService;
import com.api.doc.detail.util.DocDownloadCheckUtil;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetData;
import weaver.conn.constant.DBConstant;
import weaver.crm.Maint.CustomerInfoComInfo;
import weaver.docs.DocDetailLog;
import weaver.docs.category.DocTreeDocFieldComInfo;
import weaver.docs.category.DocTreeDocFieldManager;
import weaver.docs.category.SecCategoryComInfo;
import weaver.docs.category.SubCategoryComInfo;
import weaver.docs.docs.reply.DocReplyManager;
import weaver.docs.util.DocTriggerUtils;
import weaver.file.FileUpload;
import weaver.file.ImageFileManager;
import weaver.general.*;
import weaver.hrm.User;
import weaver.hrm.appdetach.AppDetachComInfo;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.contract.ContractTypeComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.share.ShareManager;
import weaver.system.SendToAllForNew;
import weaver.system.SysRemindWorkflow;
import weaver.system.ThreadForAllForNew;
import weaver.systeminfo.SysMaintenanceLog;
import weaver.systeminfo.setting.HrmUserSettingComInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Title: 文档处理基本类
 * Company: weaver
 * 
 * @author zh
 * @version 1.0
 */




public class DocManager extends BaseBean {

	private static DocIdUpdate docIdUpdate = new DocIdUpdate();
	
	private static ImageFileIdUpdate imageFileIdUpdate = new ImageFileIdUpdate();
	
	private static VersionIdUpdate versionIdUpdate = new VersionIdUpdate();	
		
    private ResourceComInfo hrc;

    private CustomerInfoComInfo cici;

    private DepartmentComInfo dci;
 
    private SecCategoryComInfo scc;
    
    private SubCategoryComInfo subc;
    
    
    private DocComInfo dc;


    private RecordSetData rs = new RecordSetData();
    
    private RecordSetData tmprs = new RecordSetData();
    
    private RecordSetData recorder = new RecordSetData();
    
    private RecordSetData record = new RecordSetData();
    

    private DocDetailLog log;

    private DocImageManager imgManger;

    private ContractTypeComInfo ctci = new ContractTypeComInfo();

    private String action;

    private String clientip;

    private int userid;

    private int languageid;

    private String sql_where;

    private int id; /* 文档id */
    
    private int oldVersionId;//文件版本id

    private int maincategory; /* 文档主目录 */

    private int subcategory; /* 文档分目录 */

    private int seccategory; /* 文档子目录 */

    private int doclangurage; /* 文档语言 */

    private String docapprovable; /* 是否需要审批 0:否 1:是 */

    private String docreplyable; /* 可否回复 0:否 1:是 */

    private String isreply; /* 是否回复文档 0:否 1:是 */

    private int replydocid; /* 回复文件id */

    private String docsubject; /* 文档主题 */

    private String doccontent; /* 文档内容 HTML格式 */

    private String docpublishtype;

    /*
     * 文档发布类型 1:正常(不发布) 2:新闻 3:标题新闻
     */
    private String docpublishtypeold;

    private int itemid; /* 文档中选择的物品id */

    private int itemmaincategoryid; /* 文档中选择的物品种类id */

    private int hrmresid; /* 文档中选择的人力资源id */

    private int assetid; // 文档中选择资产id

    private int ownerid; // 创建人id   调整为  文档所有者id

    private int crmid; /* 文档中选择的CRM id */

    private int projectid; /* 文档中选择的项目id */

    private int financeid; /* 文档中选择的财务-交易id */

    private int doccreaterid; /* 文档创建者id */

    private int docdepartmentid; /* 文档创建者所在部门id */

    private String doccreatedate; /* 文档创建日期 */

    private String doccreatetime; /* 文档创建时间 */

    private int doclastmoduserid; /* 文档最后修改者id */

    private String doclastmoddate; /* 文档最后修改日期 */

    private String doclastmodtime; /* 文档最后修改时间 */

    private int docapproveuserid; /* 文档审批者id */

    private String docapprovedate; /* 文档审批日期 */

    private String docapprovetime; /* 文档审批时间 */

    private int docarchiveuserid; /* 文档归档者id */

    private String docarchivedate; /* 文档归档日期 */

    private String docarchivetime; /* 文档归档时间 */

    private String docstatus; /* 文档状态:0:草稿,1:生效/正常(不需要审批，归档重新打开),2: 生效/正常(审批后,发布后),3:审批,4:退回(草稿),5:归档,6:待发布,7:失效,8:作废 */

    private String parentids; /* 文档父节点 */

    private String keyword; /* 文档的关键字 */

    private int accessorycount; /* 附件总数 */

    private int replaydoccount; /* 回复文档总数 */

    private String usertype; /* 创建的用户类型 1: 内部 2: 外部 */  //该字段调整为：当前操作用户的用户类型  1: 内部用户 2: 外部用户

    private int id2; /* remark表的id */

    private String approveremark; /* 批复意见 */

    private String isapprover; /* 是否批谁通过：是－１，否（退回）－０ */

    private String docno;

    private String topage; // link other module

    private String oldstatus; // check if the pre status is return : "4"

    private int oldownerid;

    private String contractman = ""; // 合同人

    private String contractstartdate = ""; // 合同开始日期

    private String contractenddate = ""; // 合同结束日期

    private String docmodule = ""; // 文档模板

    private String proenddate = ""; // 试用期结束日期

    private int typeid = 0; // contract type id

    private String urlfrom = ""; // 用于判断来自以及返回的页面

    // add by 王金永
    private int docType = 1;

    private int newsid = 0;// 杨国生2003-09-05加用于解决网站传递新闻组的接口

    private String canCopy = "1"; // 1：表示在查看状态下此文档不能够拷贝； 2：表示在查看状态下此文档可以拷贝

    private String canRemind = "1"; // 1：表示是否回复提醒； 1：没有回复提醒；2：有回复提醒

    // add by 董平
    private String userCatalogId = "0"; // 用户目录

    private String orderable = "0"; // 此目录下的文档是否可订阅 0,不可以 1,可以

    private String docextendname = ""; // 文档的扩展名 html doc xls ppt wps

    private String opreateType = ""; // 操作者的ID
    
    // add by wdl
    private String docCode = ""; //文档编码
    private int docEdition = -1; //文档版本
    private int docEditionId = -1; //文档版本ID
    private int isHistory = 0;//是否历史版本
    private int approveType = 0;//审批类型(1:生效审批,2:失效审批)
    
    private int mainDoc = -1; //主文档(默认当前文档)
    private int readOpterCanPrint = 0; //允许只读操作人打印 0,不允许 1,允许
    private int selectedPubMouldId = 0; //发布时所选的显示模版ID
    private int canPrintedNum = 0;//可打印份数
    
    private int docValidUserId = 0;//生效操作人
    private String docValidDate = "";//生效日期
    private String docValidTime = "";//生效时间
    
    private int docPubUserId = 0;//发布操作人
    private String docPubDate = "";//发布日期
    private String docPubTime = "";//发布时间
    
    private int docReOpenUserId = 0;//重新打开操作人
    private String docReOpenDate = "";//重新打开日期
    private String docReOpenTime = "";//重新打开时间
    
    private int docInvalUserId = 0;//失效操作人
    private String docInvalDate = "";//失效日期
    private String docInvalTime = "";//失效时间

    private String dummycata = "";//虚拟目录
    
    private int docCancelUserId = 0;//作废操作人
    private String docCancelDate = "";//作废日期
    private String docCancelTime = "";//作废时间
    
    private String invalidationDate = "";//失效时间
    
    private String checkOutStatus = "0";//签出状态  1：签出，0：未签出
    private int checkOutUserId = 0;//签出用户
    private String checkOutUserType = "";//签出用户类型   1:内部用户，2：外部用户
    private String checkOutDate = "";//签出日期
    private String checkOutTime = "";//签出时间   
    
    private String hasUsedTemplet = "";//是否已经套红
    
    private String docCreaterType; // 文档创建者类型（1:内部用户  2：外部用户）    
    private String docLastModUserType; // 文档最后修改者类型（1:内部用户  2：外部用户）    
    private String docApproveUserType; // 文档审批者类型（1:内部用户  2：外部用户）    
    private String docValidUserType; // 生效操作人类型（1:内部用户  2：外部用户）    
    private String docInvalUserType; // 失效操作人类型（1:内部用户  2：外部用户）    
    private String docArchiveUserType; // 文档归档者类型（1:内部用户  2：外部用户）    
    private String docCancelUserType; // 作废操作人类型（1:内部用户  2：外部用户）    
    private String docPubUserType; // 发布操作人类型（1:内部用户  2：外部用户）    
    private String docReopenUserType; // 重新打开操作人类型（1:内部用户  2：外部用户）    
    private String ownerType; // 文档拥有者类型（1:内部用户  2：外部用户） 
    private int secretLevel;  //文档密级
    private String secretValidity;  //文档密级期限

    private String[] customDataIdMapping; //自定义字段映射关系:"id1_id2"

    private int hrmContractId;//合同id    
    
    private FileUpload fileUpload;//FileUpload对象
    
    private ShareManager ShareManager;

	private SysMaintenanceLog SysMaintenanceLog;

	private List imageFileIdOfPicChangeList;
	
	private int editMouldId=0;//文档编辑模板id

	private int replyremind=0;//回复提醒

	private int docVestIn;
	
	private String source;

	private HrmUserSettingComInfo userSetting=null;
	
	public static final int DEFAILT_SECRET_LEVEL = 4;
	
    /**
     * 构造函数
     */
    public DocManager() {
        try {
			userSetting=new HrmUserSettingComInfo();
            hrc = new ResourceComInfo();
            dci = new DepartmentComInfo();
            cici = new CustomerInfoComInfo();
            scc = new SecCategoryComInfo();
            subc= new SubCategoryComInfo();
            log = new DocDetailLog();
            imgManger = new DocImageManager();
            ShareManager = new ShareManager();
			SysMaintenanceLog = new SysMaintenanceLog();
            dc = new DocComInfo();
            resetParameter();
        } catch (Exception ex) {
            writeLog(ex);
        }
    }

    /**
     * 重置各参数的值
     */
    public void resetParameter() {
        imgManger.resetParameter();
        this.action = "";
        clientip = "";
        userid = 0;
        languageid = 0;
        id = 0;
        this.oldVersionId=0;
        sql_where = "";
        this.maincategory = 0;
        this.subcategory = 0;
        this.seccategory = 0;
        this.doclangurage = 0;
        this.docapprovable = "";
        this.docreplyable = "";
        this.isreply = "";
        this.replydocid = 0;
        this.docsubject = "";
        this.doccontent = "";
        this.docpublishtype = "";
        this.docpublishtypeold = "";
        this.itemid = 0;
        this.itemmaincategoryid = 0;
        this.hrmresid = 0;
        this.assetid = 0;
        this.ownerid = 0;
        this.crmid = 0;
        this.projectid = 0;
        this.financeid = 0;
        this.doccreaterid = 0;
        this.docdepartmentid = 0;
        this.doccreatedate = "";
        this.doccreatetime = "";
        this.doclastmoduserid = 0;
        this.doclastmoddate = "";
        this.doclastmodtime = "";
        this.docapproveuserid = 0;
        this.docapprovedate = "";
        this.docapprovetime = "";
        this.docarchiveuserid = 0;
        this.docarchivedate = "";
        this.docarchivetime = "";
        this.docstatus = "";
        this.parentids = "";
        this.keyword = ""; /* 文档的关键字 */
        this.accessorycount = 0; /* 附件总数 */
        this.replaydoccount = 0; /* 回复文档总数 */
        this.usertype = ""; /* 创建的用户类型 1: 内部 2: 外部 */   //该字段调整为：当前操作用户的用户类型  1: 内部用户 2: 外部用户
        this.opreateType = "";

        this.id2 = 0; /* remark表的id */
        this.approveremark = ""; /* 批复意见 */
        this.isapprover = ""; /* 是否批谁通过：是－１，否（退回）－０ */
        this.docno = "";
        this.oldstatus = "";
        this.oldownerid = 0;

        this.contractman = "";
        this.contractstartdate = "";
        this.contractenddate = "";
        this.proenddate = "";
        this.typeid = 0;
        this.urlfrom = "";
        this.newsid = 0;
        this.userCatalogId = "0";
        this.docextendname = "html";
        
        
        
        this.docCode = "";
        this.docEdition = -1;
        this.docEditionId = -1;
        this.isHistory = 0;
        this.mainDoc = -1;
        this.readOpterCanPrint = 0;

        this.docValidUserId = 0;
        this.docValidDate = "";
        this.docValidTime = "";
        
        this.docPubUserId = 0;
        this.docPubDate = "";
        this.docPubTime = "";
        
        this.docReOpenUserId = 0;
        this.docReOpenDate = "";
        this.docReOpenTime = "";
        
        this.docInvalUserId = 0;
        this.docInvalDate = "";
        this.docInvalTime = "";
        
        this.docCancelUserId = 0;
        this.docCancelDate = "";
        this.docCancelTime = "";
        
        this.invalidationDate = "";
		this.dummycata = "";
        this.canPrintedNum=0;
		
        this.checkOutStatus = "0";
        this.checkOutUserId = 0;
        this.checkOutUserType = "";
        this.checkOutDate = "";
        this.checkOutTime = "";  
        
        this.hasUsedTemplet="0";
        
        this.docCreaterType="1"; 
        this.docLastModUserType=""; 
        this.docApproveUserType=""; 
        this.docValidUserType=""; 
        this.docInvalUserType=""; 
        this.docArchiveUserType=""; 
        this.docCancelUserType=""; 
        this.docPubUserType=""; 
        this.docReopenUserType="";
        this.ownerType="";

        this.hrmContractId=0;        
        this.fileUpload=null;
        
        this.imageFileIdOfPicChangeList=null;
        this.editMouldId=0;	   
        this.docVestIn = 0;
        this.secretLevel = DEFAILT_SECRET_LEVEL;
        this.secretValidity = "";
        this.replyremind = 0;
    }

    /**
     * 设置个人文档目录
     * 
     * @param userCatalogId 个人文档目录
     */
    public void setUserCatalogId(String userCatalogId) {
        this.userCatalogId = userCatalogId;
    }

    /**
     * 返回个人文档目录
     * 
     * @return 个人文档目录
     */
    public String getUserCatalogId() {
        return this.userCatalogId;
    }

    /**
     * 设置 sql条件语句
     * 
     * @param sql sql条件语句
     */
    public void setSql_where(String sql) {
        this.sql_where = sql;
    }

    /**
     * 设置文档id
     * 
     * @param id 文档id
     */
    public void setId(int id) {
        this.id = id;
    }

    /**
     * 设置用户语言ID
     * 
     * @param id 用户语言ID
     */
    public void setLanguageid(int id) {
        this.languageid = id;
    }

    /**
     * 设置文档主目录
     * 
     * @param maincategory 文档主目录
     */
    public void setMaincategory(int maincategory) {
        this.maincategory = maincategory;
    }

    /**
     * 设置文档分目录
     * 
     * @param subcategory 文档分目录
     */
    public void setSubcategory(int subcategory) {
        this.subcategory = subcategory;
    }

    /**
     * 设置文档子目录
     * 
     * @param seccategory 文档子目录
     */
    public void setSeccategory(int seccategory) {
        this.seccategory = seccategory;
    }

    /**
     * 设置文档语言
     * 
     * @param doclangurage 文档语言
     */
    public void setDoclangurage(int doclangurage) {
        this.doclangurage = doclangurage;
    }

    /**
     * 设置 是否需要审批 0:否 1:是
     * 
     * @param docapprovable 是否需要审批 0:否 1:是
     */
    public void setDocapprovable(String docapprovable) {
        this.docapprovable = docapprovable;
    }

    /**
     * 设置可否回复
     * 
     * @param docreplyable 可否回复 0:否 1:是
     */
    public void setDocreplyable(String docreplyable) {
        this.docreplyable = docreplyable;
    }

    /**
     * 是否回复文档
     * 
     * @param isreply 是否回复文档
     */
    public void setIsreply(String isreply) {
        this.isreply = isreply;
    }

    /**
     * 回复文件id
     * 
     * @param replydocid 回复文件id
     */
    public void setReplydocid(int replydocid) {
        this.replydocid = replydocid;
    }

    /**
     * 设置文档主题
     * 
     * @param docsubject 文档主题
     */
    public void setDocsubject(String docsubject) {
        this.docsubject = docsubject;
    }

    /**
     * 设置文档内容
     * 
     * @param doccontent 文档内容
     */
    public void setDoccontent(String doccontent) {
        this.doccontent = doccontent;
    }

    /**
     * 设置文档发布类型
     * 
     * @param docpublishtype 文档发布类型 1:正常(不发布) 2:新闻 3:标题新闻
     */
    public void setDocpublishtype(String docpublishtype) {
        if ("".equals(docpublishtype))
            docpublishtype = "1";
        this.docpublishtype = docpublishtype;
    }

    /**
     * 设置 文档中选择的物品id
     * 
     * @param itemid 文档中选择的物品id
     */
    public void setItemid(int itemid) {
        this.itemid = itemid;
    }

    /**
     * 设置文档中选择的物品种类id
     * 
     * @param itemmaincategoryid 文档中选择的物品种类id
     */
    public void setItemmaincategoryid(int itemmaincategoryid) {
        this.itemmaincategoryid = itemmaincategoryid;
    }

    /**
     * 设置文档中选择的人力资源id
     * 
     * @param hrmresid 文档中选择的人力资源id
     */
    public void setHrmresid(int hrmresid) {
        this.hrmresid = hrmresid;
    }

    /**
     * 设置文档中选择资产id
     * 
     * @param assetid 文档中选择资产id
     */
    public void setAssetid(int assetid) {
        this.assetid = assetid;
    }

    /**
     * 设置 所有者id
     * 
     * @param ownerid 所有者id
     */
    public void setOwnerid(int ownerid) {
        this.ownerid = ownerid;
    }

    /**
     * 设置 文档中选择的CRM id
     * 
     * @param crmid 文档中选择的CRM id
     */
    public void setCrmid(int crmid) {
        this.crmid = crmid;
    }

    /**
     * 设置文档中选择的项目id
     * 
     * @param projectid 文档中选择的项目id
     */
    public void setProjectid(int projectid) {
        this.projectid = projectid;
    }

    /**
     * 设置文档中选择的财务-交易id
     * 
     * @param financeid 文档中选择的财务-交易id
     */
    public void setFinanceid(int financeid) {
        this.financeid = financeid;
    }

    /**
     * 设置文档创建者id
     * 
     * @param doccreaterid 文档创建者id
     */
    public void setDoccreaterid(int doccreaterid) {
        this.doccreaterid = doccreaterid;
    }

    /**
     * 设置文档创建者所在部门id
     * 
     * @param docdepartmentid 文档创建者所在部门id
     */
    public void setDocdepartmentid(int docdepartmentid) {
        this.docdepartmentid = docdepartmentid;
    }

    /**
     * 设置文档创建日期
     * 
     * @param doccreatedate 文档创建日期
     */
    public void setDoccreatedate(String doccreatedate) {
        this.doccreatedate = doccreatedate;
    }

    /**
     * 设置文档创建时间
     * 
     * @param doccreatetime 文档创建时间
     */
    public void setDoccreatetime(String doccreatetime) {
        this.doccreatetime = doccreatetime;
    }

    /**
     * 设置文档最后修改者id
     * 
     * @param doclastmoduserid 文档最后修改者id
     */
    public void setDoclastmoduserid(int doclastmoduserid) {
        this.doclastmoduserid = doclastmoduserid;
    }

    /**
     * 设置文档最后修改日期
     * 
     * @param doclastmoddate 文档最后修改日期
     */
    public void setDoclastmoddate(String doclastmoddate) {
        this.doclastmoddate = doclastmoddate;
    }

    /**
     * 设置文档最后修改时间
     * 
     * @param doclastmodtime 文档最后修改时间
     */
    public void setDoclastmodtime(String doclastmodtime) {
        this.doclastmodtime = doclastmodtime;
    }

    /**
     * 设置文档审批者id
     * 
     * @param docapproveuserid 文档审批者id
     */
    public void setDocapproveuserid(int docapproveuserid) {
        this.docapproveuserid = docapproveuserid;
    }

    /**
     * 设置文档审批日期
     * 
     * @param docapprovedate 文档审批日期
     */
    public void setDocapprovedate(String docapprovedate) {
        this.docapprovedate = docapprovedate;
    }

    /**
     * 设置文档审批时间
     * 
     * @param docapprovetime 文档审批时间
     */
    public void setDocapprovetime(String docapprovetime) {
        this.docapprovetime = docapprovetime;
    }

    /**
     * 设置文档归档者id
     * 
     * @param docarchiveuserid 文档归档者id
     */
    public void setDocarchiveuserid(int docarchiveuserid) {
        this.docarchiveuserid = docarchiveuserid;
    }

    /**
     * 设置文档归档日期
     * 
     * @param docarchivedate 文档归档日期
     */
    public void setDocarchivedate(String docarchivedate) {
        this.docarchivedate = docarchivedate;
    }

    /**
     * 设置文档归档时间
     * 
     * @param docarchivetime 文档归档时间
     */
    public void setDocarchivetime(String docarchivetime) {
        this.docarchivetime = docarchivetime;
    }

    /**
     * 设置文档状态
     * 
     * @param docstatus 文档状态
     */
    public void setDocstatus(String docstatus) {
        this.docstatus = docstatus;
    }

    /**
     * 设置文档父节点
     * 
     * @param parentids 文档父节点
     */
    public void setParentids(String parentids) {
        this.parentids = parentids;
    }

    /**
     * 设置文档的关键字
     * 
     * @param keyword 文档的关键字
     */
    public void setKeyword(String keyword) {
        this.keyword = keyword;
    }

    /**
     * 设置 附件总数
     * 
     * @param accessorycount 附件总数
     */
    public void setAccessorycount(int accessorycount) {
        this.accessorycount = accessorycount;
    }

    /**
     * 设置回复文档总数
     * 
     * @param replaydoccount 回复文档总数
     */
    public void setReplaydoccount(int replaydoccount) {
        this.replaydoccount = replaydoccount;
    }

    /**
     * 设置创建的用户类型
     * 
     * @param usertype 创建的用户类型
     */
    public void setUsertype(String usertype) {
        this.usertype = usertype;
    }

    /**
     * 设置remark表的id
     * 
     * @param id2 remark表的id
     */
    public void setId2(int id2) {
        this.id2 = id2;
    }

    /**
     * 设置
     * 
     * @param approveremark
     */
    public void setApproveremark(String approveremark) {
        this.approveremark = approveremark;
    }

    /**
     * 设置批复意见
     * 
     * @param isapprover 批复意见
     */
    public void setIsapprover(String isapprover) {
        this.isapprover = isapprover;
    }

    /**
     * 设置跳转页面
     * 
     * @param topage 跳转页面
     */
    public void setToPage(String topage) {
        this.topage = topage;
    }

    /**
     * 设置文档归档编号
     * 
     * @param docno 文档归档编号
     */
    public void setDocno(String docno) {
        this.docno = docno;
    }

    /**
     * 设置合同人
     * 
     * @param contractman 合同人
     */
    public void setContractMan(String contractman) {
        this.contractman = contractman;
    }

    /**
     * 设置合同开始日期
     * 
     * @param contractstartdate 合同开始日期
     */
    public void setContractStartDate(String contractstartdate) {
        this.contractstartdate = contractstartdate;
    }

    /**
     * 设置合同结束日期
     * 
     * @param contractenddate 合同结束日期
     */
    public void setContractEndDate(String contractenddate) {
        this.contractenddate = contractenddate;
    }

    /**
     * 设置文档模板
     * 
     * @param docmodule 文档模板
     */
    public void setDocModule(String docmodule) {
        this.docmodule = docmodule;
    }

    /**
     * 设置试用期结束日期
     * 
     * @param proenddate 试用期结束日期
     */
    public void setProEndDate(String proenddate) {
        this.proenddate = proenddate;
    }

    /**
     * 设置客户类型ID
     * 
     * @param typeid 客户类型ID
     */
    public void setContractType(int typeid) {
        this.typeid = typeid;
    }

    /**
     * 设置用于判断来自以及返回的页面
     * 
     * @param urlfrom 用于判断来自以及返回的页面
     */
    public void setUrlFrom(String urlfrom) {
        this.urlfrom = urlfrom;
    }

    /**
     * 设置解决网站传递新闻组的接口
     * 
     * @param newsid 解决网站传递新闻组的接口
     */
    public void setNewsId(int newsid) {
        this.newsid = newsid;
    }

    /**
     * 设置 能否拷贝
     * 
     * @param canCopy 能否拷贝 1：表示在查看状态下此文档不能够拷贝； 2：表示在查看状态下此文档可以拷贝
     */
    public void setCanCopy(String canCopy) {
        this.canCopy = canCopy;
    }

    /**
     * 设置能否提醒
     * 
     * @param canRemind 能否提醒 1：表示是否回复提醒； 1：没有回复提醒；2：有回复提醒
     */
    public void setCanRemind(String canRemind) {
        this.canRemind = canRemind;
    }

    /**
     * 设置文件扩展名
     * 
     * @param docextendname 文件扩展名
     */
    public void setDocextendname(String docextendname) {
        this.docextendname = docextendname;
    }

    /**
     * 返回文件扩展名
     * 
     * @return 文件扩展名
     */
    public String getDocextendname() {
        return this.docextendname;
    }

    /**
     * 返回文档id
     * 
     * @return 文档id
     */
    public int getId() {
        return id;
    }

    /**
     * 返回新闻ID
     * 
     * @return 新闻ID
     * @throws Exception
     */
    public int getNewsId() throws Exception {
        return this.newsid;
    }
    
    public int getSecretLevel() throws Exception{
    	return this.secretLevel;
    }
    public void setSecretLevel(int secretLevel){
    	this.secretLevel = secretLevel;
    }

    public String getSecretValidity() {
        return secretValidity;
    }

    public void setSecretValidity(String secretValidity) {
        this.secretValidity = secretValidity;
    }

    public int getDocSecretLevel() throws Exception{
    	return rs.getInt("secretLevel");
    }
    public String getDocSecretValidity() throws Exception{
        return rs.getString("secretValidity");
    }
    public int getReplyremind() {
        return this.replyremind;
    }

    public void setReplyremind(int replyremind) {
        this.replyremind = replyremind;
    }

    public int getDocReplyremind() {
        return rs.getInt("replyremind");
    }
    /**
     * 返回 文档ID
     * 
     * @return 文档ID
     * @throws Exception
     */
    public int getDocid() throws Exception {
        return rs.getInt("id");
    }

    /**
     * 返回文档类型
     * 
     * @return 文档类型
     * @throws Exception
     */
    public int getDocType() throws Exception {
        return rs.getInt("doctype");
    }

    /**
     * 返回能否拷贝
     * 
     * @return 能否拷贝
     * @throws Exception
     */
    public String getCanCopy() throws Exception {
        return rs.getString("cancopy");
    }

    /**
     * 返回能否提醒
     * 
     * @return 能否提醒
     * @throws Exception
     */
    public String getCanRemind() throws Exception {
        return rs.getString("canremind");
    }

    /**
     * 返回文档主目录
     * 
     * @return 文档主目录
     * @throws Exception
     */
    public int getMaincategory() throws Exception {
        return rs.getInt("maincategory");
    }

    /**
     * 返回文档分目录
     * 
     * @return 文档分目录
     * @throws Exception
     */
    public int getSubcategory() throws Exception {
        return rs.getInt("subcategory");
    }

    /**
     * 返回文档子目录
     * 
     * @return 文档子目录
     * @throws Exception
     */
    public int getSeccategory() throws Exception {
        return rs.getInt("seccategory");
    }

    /**
     * 返回文档语言
     * 
     * @return 文档语言
     * @throws Exception
     */
    public int getDoclangurage() throws Exception {
        return rs.getInt("doclangurage");
    }

    /**
     * 返回是否需要审批
     * 
     * @return 是否需要审批 0:否 1:是
     * @throws Exception
     */
    public String getDocapprovable() throws Exception {
        return rs.getString("docapprovable");
    }

    /**
     * 返回 可否回复
     * 
     * @return 可否回复 0:否 1:是
     * @throws Exception
     */
    public String getDocreplyable() throws Exception {
        return rs.getString("docreplyable");
    }

    /**
     * 返回是否回复文档
     * 
     * @return 是否回复文档
     * @throws Exception
     */
    public String getIsreply() throws Exception {
        return rs.getString("isreply");
    }

    /**
     * 返回回复文件id
     * 
     * @return 回复文件id
     * @throws Exception
     */
    public int getReplydocid() throws Exception {
        return rs.getInt("replydocid");
    }

    /**
     * 返回文档主题
     * 
     * @return 文档主题
     * @throws Exception
     */
    public String getDocsubject() throws Exception {
    	String docsubject_tmp = Util.null2String(rs.getString("docsubject"));
    	docsubject_tmp = docsubject_tmp.replaceAll("\n", "");//TD11607
        return docsubject_tmp;
    }

    /**
     * 返回文档内容
     * 
     * @return 文档内容
     * @throws Exception
     */
    public String getDoccontent() throws Exception {
        return Util.toBaseEncoding(rs.getString("doccontent"), languageid, "1");
    }

    /**
     * 返回 文档发布类型
     * 
     * @return 文档发布类型
     * @throws Exception
     */
    public String getDocpublishtype() throws Exception {
        String tempDocpublishtype = Util.null2String(rs.getString("docpublishtype"));
        if ("".equals(tempDocpublishtype))
            tempDocpublishtype = "1";
        return tempDocpublishtype;
    }

    /**
     * 返回文档中选择的物品id
     * 
     * @return 文档中选择的物品id
     * @throws Exception
     */
    public int getItemid() throws Exception {
        return rs.getInt("itemid");
    }

    /**
     * 返回文档中选择的物品种类id
     * 
     * @return 文档中选择的物品种类id
     * @throws Exception
     */
    public int getItemmaincategoryid() throws Exception {
        return rs.getInt("itemmaincategoryid");
    }

    /**
     * 返回
     * 
     * @return
     * @throws Exception
     */
    public int getHrmresid() throws Exception {
        return rs.getInt("hrmresid");
    }

    /**
     * 返回文档中选择的人力资源id
     * 
     * @return 文档中选择的人力资源id
     * @throws Exception
     */
    public int getCrmid() throws Exception {
        return rs.getInt("crmid");
    }

    /**
     * 返回文档中选择的项目id
     * 
     * @return 返回文档中选择的项目id
     * @throws Exception
     */
    public int getProjectid() throws Exception {
        return rs.getInt("projectid");
    }

    /**
     * 返回文档中选择的财务-交易id
     * 
     * @return 文档中选择的财务-交易id
     * @throws Exception
     */
    public int getFinanceid() throws Exception {
        return rs.getInt("financeid");
    }

    /**
     * 返回文档创建者id
     * 
     * @return 文档创建者id
     * @throws Exception
     */
    public int getDoccreaterid() throws Exception {
        return rs.getInt("doccreaterid");
    }
    /**
     * 获取阅读次数
     * @return
     * @throws Exception
     */
    public int getReadCount() throws Exception {
        return rs.getInt("readCount");
    }
    /**
     * 返回 文档创建者所在部门id
     * 
     * @return 文档创建者所在部门id
     * @throws Exception
     */
    public int getDocdepartmentid() throws Exception {
        return rs.getInt("docdepartmentid");
    }

    /**
     * 返回文档创建日期
     * 
     * @return 文档创建日期
     * @throws Exception
     */
    public String getDoccreatedate() throws Exception {
        return rs.getString("doccreatedate");
    }

    /**
     * 返回文档创建时间
     * 
     * @return 文档创建时间
     * @throws Exception
     */
    public String getDoccreatetime() throws Exception {
        return rs.getString("doccreatetime");
    }

    /**
     * 返回文档最后修改者id
     * 
     * @return 文档最后修改者id
     * @throws Exception
     */
    public int getDoclastmoduserid() throws Exception {
        return rs.getInt("doclastmoduserid");
    }

    /**
     * 返回文档最后修改日期
     * 
     * @return 文档最后修改日期
     * @throws Exception
     */
    public String getDoclastmoddate() throws Exception {
        return rs.getString("doclastmoddate");
    }

    /**
     * 返回文档最后修改时间
     * 
     * @return 文档最后修改时间
     * @throws Exception
     */
    public String getDoclastmodtime() throws Exception {
        return rs.getString("doclastmodtime");
    }

    /**
     * 返回文档审批者id
     * 
     * @return 文档审批者id
     * @throws Exception
     */
    public int getDocapproveuserid() throws Exception {
        return rs.getInt("docapproveuserid");
    }

    /**
     * 返回文档审批日期
     * 
     * @return 文档审批日期
     * @throws Exception
     */
    public String getDocapprovedate() throws Exception {
        return rs.getString("docapprovedate");
    }

    /**
     * 返回文档审批时间
     * 
     * @return 文档审批时间
     * @throws Exception
     */
    public String getDocapprovetime() throws Exception {
        return rs.getString("docapprovetime");
    }

    /**
     * 返回文档归档者id
     * 
     * @return 文档归档者id
     * @throws Exception
     */
    public int getDocarchiveuserid() throws Exception {
        return rs.getInt("docarchiveuserid");
    }

    /**
     * 返回文档归档日期
     * 
     * @return 文档归档日期
     * @throws Exception
     */
    public String getDocarchivedate() throws Exception {
        return rs.getString("docarchivedate");
    }

    /**
     * 返回文档归档时间
     * 
     * @return 文档归档时间
     * @throws Exception
     */
    public String getDocarchivetime() throws Exception {
        return rs.getString("docarchivetime");
    }

    /**
     * 返回文档状态
     * 
     * @return 文档状态
     * @throws Exception
     */
    public String getDocstatus() throws Exception {
        return rs.getString("docstatus");
    }

    /**
     * 返回文档父节点
     * 
     * @return 文档父节点
     * @throws Exception
     */
    public String getParentids() throws Exception {
        return rs.getString("parentids");
    }

    /**
     * 返回Assetid
     * 
     * @return Assetid
     * @throws Exception
     */
    public int getAssetid() throws Exception {
        return rs.getInt("assetid");
    }

    /**
     * 返回 文档所有者ID
     * 
     * @return 文档所有者ID
     * @throws Exception
     */
    public int getOwnerid() throws Exception {
        return rs.getInt("ownerid");
    }

    /**
     * 返回文档的关键字
     * 
     * @return 文档的关键字
     * @throws Exception
     */
    public String getKeyword() throws Exception {
        return rs.getString("keyword");
    }

    /**
     * 返回附件总数
     * 
     * @return 附件总数
     * @throws Exception
     */
    public int getAccessorycount() throws Exception {
        return rs.getInt("accessorycount");
    }

    /**
     * 返回回复文档总数
     * 
     * @return 回复文档总数
     * @throws Exception
     */
    public int getReplaydoccount() throws Exception {
        return rs.getInt("replaydoccount");
    }

    /**
     * 返回创建的用户类型
     * 
     * @return 创建的用户类型
     * @throws Exception
     */
    public String getUsertype() throws Exception {
        return rs.getString("usertype");
    }

    /**
     * 返回文档归档编号
     * 
     * @return 文档归档编号
     * @throws Exception
     */
    public String getDocno() throws Exception {
        return rs.getString("docno");
    }
    
    /**
     * 返回remark表的id
     * 
     * @return remark表的id
     * @throws Exception
     */
    public int getId2() throws Exception {
        return rs.getInt("id");
    }

    /**
     * 返回批复意见
     * 
     * @return 批复意见
     * @throws Exception
     */
    public String getApproveremark() throws Exception {
        return rs.getString("approveremark");
    }

    /**
     * 返回可打印份数
     * 
     * @return 可打印份数
     * @throws Exception
     */
    public int getCanPrintedNum() throws Exception {
        return Util.getIntValue(rs.getString("canPrintedNum"),0);
    }   
    
    /**
     * 返回  编辑模板id
     * 
     * @return 编辑模板id
     * @throws Exception
     */
    public int getEditMouldId() throws Exception {
        return Util.getIntValue(rs.getString("editMouldId"),0);
    }
    
    /**
     * 返回是否批谁通过：是－１，否（退回）－０
     * 
     * @return 是否批谁通过：是－１，否（退回）－０
     * @throws Exception
     */
    public String getIsapprover() throws Exception {
        return rs.getString("isapprover");
    }

    /**
     * 返回文档主目录
     * 
     * @return 文档主目录
     * @throws Exception
     */
    public int getMaincategory2() throws Exception {
        return this.maincategory;
    }

    /**
     * 返回文档分目录
     * 
     * @return 文档分目录
     * @throws Exception
     */
    public int getSubcategory2() throws Exception {
        return this.subcategory;
    }

    /**
     * 返回文档子目录
     * 
     * @return 文档子目录
     * @throws Exception
     */
    public int getSeccategory2() throws Exception {
        return this.seccategory;
    }

    /**
     * 返回文档语言
     * 
     * @return 文档语言
     * @throws Exception
     */
    public int getDoclangurage2() throws Exception {
        return this.doclangurage;
    }

    /**
     * 返回是否需要审批
     * 
     * @return 是否需要审批
     * @throws Exception
     */
    public String getDocapprovable2() throws Exception {
        return this.docapprovable;
    }

    /**
     * 返回可否回复
     * 
     * @return 可否回复
     * @throws Exception
     */
    public String getDocreplyable2() throws Exception {
        return this.docreplyable;
    }

    /**
     * 返回是否回复文档
     * 
     * @return 是否回复文档
     * @throws Exception
     */
    public String getIsreply2() throws Exception {
        return this.isreply;
    }

    /**
     * 返回回复文件id
     * 
     * @return 回复文件id
     * @throws Exception
     */
    public int getReplydocid2() throws Exception {
        return this.replydocid;
    }

    /**
     * 返回文档主题
     * 
     * @return 文档主题
     * @throws Exception
     */
    public String getDocsubject2() throws Exception {
    	String docsubject_tmp = Util.null2String(this.docsubject);
    	docsubject_tmp = docsubject_tmp.replaceAll("\n", "");//TD11607
        return docsubject_tmp;
    }

    /**
     * 返回文档内容
     * 
     * @return 文档内容
     * @throws Exception
     */
    public String getDoccontent2() throws Exception {
        return this.doccontent;
    }

    /**
     * 返回文档发布类型
     * 
     * @return 文档发布类型
     * @throws Exception
     */
    public String getDocpublishtype2() throws Exception {
        return this.docpublishtype;
    }

    /**
     * 返回文档的发布类型
     * 
     * @return 文档的发布类型
     * @throws Exception
     */
    public String getDocpublishtypeold() throws Exception {
        return this.docpublishtypeold;
    }

    /**
     * 返回文档中选择的物品id
     * 
     * @return 文档中选择的物品id
     * @throws Exception
     */
    public int getItemid2() throws Exception {
        return this.itemid;
    }

    /**
     * 返回文档中选择的物品种类id
     * 
     * @return 文档中选择的物品种类id
     * @throws Exception
     */
    public int getItemmaincategoryid2() throws Exception {
        return this.itemmaincategoryid;
    }

    /**
     * 返回文档中选择的人力资源id
     * 
     * @return 文档中选择的人力资源id
     * @throws Exception
     */
    public int getHrmresid2() throws Exception {
        return this.hrmresid;
    }

    /**
     * 文档中选择的CRM id
     * 
     * @return 文档中选择的CRM id
     * @throws Exception
     */
    public int getCrmid2() throws Exception {
        return this.crmid;
    }

    /**
     * 返回文档中选择的项目id
     * 
     * @return 文档中选择的项目id
     * @throws Exception
     */
    public int getProjectid2() throws Exception {
        return this.projectid;
    }

    /**
     * 返回档中选择的财务-交易id
     * 
     * @return 档中选择的财务-交易id
     * @throws Exception
     */
    public int getFinanceid2() throws Exception {
        return this.financeid;
    }

    /**
     * 返回文档创建者id
     * 
     * @return 文档创建者id
     * @throws Exception
     */
    public int getDoccreaterid2() throws Exception {
        return this.doccreaterid;
    }

    /**
     * 返回文档创建者所在部门id
     * 
     * @return 文档创建者所在部门id
     * @throws Exception
     */
    public int getDocdepartmentid2() throws Exception {
        return this.docdepartmentid;
    }

    /**
     * 返回文档创建日期
     * 
     * @return 文档创建日期
     * @throws Exception
     */
    public String getDoccreatedate2() throws Exception {
        return this.doccreatedate;
    }

    /**
     * 返回文档创建时间
     * 
     * @return 文档创建时间
     * @throws Exception
     */
    public String getDoccreatetime2() throws Exception {
        return this.doccreatetime;
    }

    /**
     * 返回文档最后修改者id
     * 
     * @return 文档最后修改者id
     * @throws Exception
     */
    public int getDoclastmoduserid2() throws Exception {
        return this.doclastmoduserid;
    }

    /**
     * 返回文档最后修改日期
     * 
     * @return 文档最后修改日期
     * @throws Exception
     */
    public String getDoclastmoddate2() throws Exception {
        return this.doclastmoddate;
    }

    /**
     * 返回文档最后修改时间
     * 
     * @return 文档最后修改时间
     * @throws Exception
     */
    public String getDoclastmodtime2() throws Exception {
        return this.doclastmodtime;
    }

    /**
     * 返回文档审批者id
     * 
     * @return 文档审批者id
     * @throws Exception
     */
    public int getDocapproveuserid2() throws Exception {
        return this.docapproveuserid;
    }

    /**
     * 返回文档审批日期
     * 
     * @return 文档审批日期
     * @throws Exception
     */
    public String getDocapprovedate2() throws Exception {
        return this.docapprovedate;
    }

    /**
     * 返回文档审批时间
     * 
     * @return 文档审批时间
     * @throws Exception
     */
    public String getDocapprovetime2() throws Exception {
        return this.docapprovetime;
    }

    /**
     * 返回文档归档者id
     * 
     * @return 文档归档者id
     * @throws Exception
     */
    public int getDocarchiveuserid2() throws Exception {
        return this.docarchiveuserid;
    }

    /**
     * 返回文档归档日期
     * 
     * @return 文档归档日期
     * @throws Exception
     */
    public String getDocarchivedate2() throws Exception {
        return this.docarchivedate;
    }

    /**
     * 返回文档归档时间
     * 
     * @return 文档归档时间
     * @throws Exception
     */
    public String getDocarchivetime2() throws Exception {
        return this.docarchivetime;
    }

    /**
     * 返回文档状态
     * 
     * @return 文档状态
     * @throws Exception
     */
    public String getDocstatus2() throws Exception {
        return this.docstatus;
    }

    /**
     * 返回文档父节点
     * 
     * @return 文档父节点
     * @throws Exception
     */
    public String getParentids2() throws Exception {
        return this.parentids;
    }

    /**
     * 返回Assetid
     * 
     * @return Assetid
     * @throws Exception
     */
    public int getAssetid2() throws Exception {
        return this.assetid;
    }

    /**
     * 返回 文档所有者ID
     * 
     * @return 文档所有者
     * @throws Exception
     */
    public int getOwnerid2() throws Exception {
        return this.ownerid;
    }

    /**
     * 返回文档的关键字
     * 
     * @return 文档的关键字
     * @throws Exception
     */
    public String getKeyword2() throws Exception {
        return this.keyword;
    }

    /**
     * 返回附件总数
     * 
     * @return 附件总数
     * @throws Exception
     */
    public int getAccessorycount2() throws Exception {
        return this.accessorycount;
    }

    /**
     * 返回回复文档总数
     * 
     * @return 回复文档总数
     * @throws Exception
     */
    public int getReplaydoccount2() throws Exception {
        return this.replaydoccount;
    }

    /**
     * 返回创建的用户类型
     * 
     * @return 创建的用户类型
     * @throws Exception
     */
    public String getUsertype2() throws Exception {
        return this.usertype;
    }

    /**
     * 返回remark表的id
     * 
     * @return remark表的id
     * @throws Exception
     */
    public String getDocno2() throws Exception {
        return this.docno;
    }

    /**
     * 返回批复意见
     * 
     * @return 批复意见
     * @throws Exception
     */
    public String getApproveremark2() throws Exception {
        return this.approveremark;
    }

    /**
     * 返回 是否批谁通过：是－１，否（退回）－０
     * 
     * @return 是否批谁通过：是－１，否（退回）－０
     * @throws Exception
     */
    public String getIsapprover2() throws Exception {
        return this.isapprover;
    }

    /**
     * 返回合同人
     * 
     * @return 合同人
     */
    public String getContractMan() {
        return this.contractman;
    }

    /**
     * 返回合同开始日期
     * 
     * @return 合同开始日期
     */
    public String getContractStartDate() {
        return this.contractstartdate;
    }

    /**
     * 返回合同结束日期
     * 
     * @return 合同结束日期
     */
    public String getContractEndDate() {
        return this.contractenddate;
    }

    /**
     * 返回文档模板
     * 
     * @return 文档模板
     */
    public String getDocModule() {
        return this.docmodule;
    }

    /**
     * 返回试用期结束日期
     * 
     * @return 试用期结束日期
     */
    public String getProEndDate() {
        return this.proenddate;
    }

    /**
     * 返回联系人类型ID
     * 
     * @return 联系人类型ID
     */
    public int getContractType() {
        return this.typeid;
    }

    /**
     * 返回需返回的页面URL
     * 
     * @return 需返回的页面URL
     */
    public String getUrlFrom() {
        return this.urlfrom;
    }

    /**
     * 返回需返回的页面URL
     * 
     * @return 需返回的页面URL
     */
    public String getToPage() {
        if(this.topage==null||this.topage.trim().equals("")){
        	this.topage="";
        }
    	return topage;
    }

    /**
     * 返回上一次的状态
     * 
     * @return 上一次的状态
     */
    public String getOldstatus() {
        return oldstatus;
    }

    /**
     * 返回上一次的所有者的ID
     * 
     * @return 上一次的所有者的ID
     */
    public int getOldownerid() {
        return oldownerid;
    }

    /**
     * 设置操作类型
     * 
     * @param action 操作类型
     */
    public void setAction(String action) {
        this.action = Util.null2String(action);
    }

    /**
     * 设置当前客户端IP
     * 
     * @param ip 客户端IP
     */
    public void setClientAddress(String ip) {
        this.clientip = ip;
    }

    /**
     * 设置当前用户ID
     * 
     * @param id 当前用户ID
     */
    public void setUserid(int id) {
        this.userid = id;
    }

    /**
     * 返回FileUpload对象
     * 
     * @return FileUpload对象
     * @throws Exception
     */
    public FileUpload getFileUpload2() {
        return this.fileUpload;
    }    
    
    
    public int getDocVestIn() {
        return rs.getInt("docVestIn");
    }

    public void setDocVestIn(int docVestIn) {
        this.docVestIn = docVestIn;
    }

    /**
     * 选择新闻信息
     * 
     * @param newsclause sql条件
     * @param user user对象
     * @throws Exception
     */
    public void selectNewsDocInfo(String newsclause, User user) throws Exception {
        RecordSet rsSql = new RecordSet();
        String dbtype = rsSql.getDBType();
        boolean isoracle = dbtype.equals(DBConstant.DB_TYPE_ORACLE);
        boolean ismysql = dbtype.equals(DBConstant.DB_TYPE_MYSQL);

        String userid = "" + user.getUID();
        String logintype = Util.null2String(user.getLogintype());
        String usertype = "" + user.getType();
        String seclevel = user.getSeclevel();

        String sql = "";

        if (isoracle || ismysql) {
            sql = " select a.id,a.docsubject,b.doccontent,a.doccreatedate,a.doccreaterid, a.usertype,a.doclastmoddate,a.doclastmodtime from DocDetail a,DocDetailContent b "
                    + " where id in (select distinct t1.id from "
                    + " DocDetail  t1,"
                    + ShareManager.getShareDetailTableByUserNew("doc", user)
                    + " t2,DocDetailContent t3 "
                    + " where t1.id=t2.sourceid and t1.id = t3.docid "
                    + newsclause+this.getDateDuringSql(this.getDateDuringForHp())
                    + ")  and a.id=b.docid order by doclastmoddate desc, doclastmodtime desc";
        } else {
            sql = " select id,docsubject,doccontent,doccreatedate,doccreaterid, usertype from DocDetail "
                    + " where id in (select distinct t1.id from " + " DocDetail  t1,"
                    + ShareManager.getShareDetailTableByUserNew("doc", user) + " t2 " + " where t1.id=t2.sourceid "
                    + newsclause + this.getDateDuringSql(this.getDateDuringForHp())+")  order by doclastmoddate desc, doclastmodtime desc";
        }
        rsSql.executeSql(sql);
        rs = rsSql.getData();
    }
    /**
     * 和selectNewsDocInfo 的唯一区别就是只返回id
     * 
     * @param newsclause sql条件
     * @param user user对象
     * @throws Exception
     */
    public void selectNewsDocIdInfo(String newsclause, User user) throws Exception {
        RecordSet rsSql = new RecordSet();
        String dbtype = rsSql.getDBType();
        boolean isoracle = dbtype.equals(DBConstant.DB_TYPE_ORACLE);
        boolean ismysql = dbtype.equals(DBConstant.DB_TYPE_MYSQL);
        
//        String userid = "" + user.getUID();
//        String logintype = Util.null2String(user.getLogintype());
//        String usertype = "" + user.getType();
//        String seclevel = user.getSeclevel();
        
        String sql = "";
        
        if (isoracle || ismysql) {
            sql = " select a.id from DocDetail a,DocDetailContent b "
                + " where id in (select distinct t1.id from "
                + " DocDetail  t1,"
                + ShareManager.getShareDetailTableByUserNew("doc", user)
                + " t2,DocDetailContent t3 "
                + " where t1.id=t2.sourceid and t1.id = t3.docid "
                + newsclause+this.getDateDuringSql(this.getDateDuringForHp())
                + ")  and a.id=b.docid order by doclastmoddate desc, doclastmodtime desc";
        } else {
            sql = " select id from DocDetail "
                + " where id in (select distinct t1.id from " + " DocDetail  t1,"
                + ShareManager.getShareDetailTableByUserNew("doc", user) + " t2 " + " where t1.id=t2.sourceid "
                + newsclause + this.getDateDuringSql(this.getDateDuringForHp())+")  order by doclastmoddate desc, doclastmodtime desc";
        }
        rsSql.executeSql(sql);
        rs = rsSql.getData();
    }

    /**
     * 选择文档信息
     * 
     * @param newsclause sql条件
     * @param user user对象
     * @throws Exception
     */
    public void selectNewsDocInfo(String newsclause, User user, int perpage, int pagenum) throws Exception {
        RecordSet rsSql = new RecordSet();
        String dbtype = rsSql.getDBType();
        boolean isoracle = dbtype.equals(DBConstant.DB_TYPE_ORACLE);
        boolean ismysql = dbtype.equals(DBConstant.DB_TYPE_MYSQL);
        SplitPageParaBean sppb = new SplitPageParaBean();
        SplitPageUtil spu = new SplitPageUtil();
		String belongtoshow = userSetting.getBelongtoshowByUserId(user.getUID()+""); 
	    String belongtoids =  user.getBelongtoids();
	    String account_type = user.getAccount_type();
        if (isoracle || ismysql) { // oralce

            //sppb .setBackFields("a.id,a.docsubject,b.doccontent,a.doclastmoddate,a.doclastmodtime,a.doccreaterid, a.usertype,a.doccreatedate,a.doccreatetime");
			if(belongtoshow.equals("1")&&account_type.equals("0")&&!belongtoids.equals("")){
			 belongtoids+=","+user.getUID();
			 	if(isoracle)
			 		sppb.setOutfields("b.doccontent, nvl((select sum(readcount) from docReadTag where userType ="+user.getLogintype()+" and docid=r.id and userid in("+belongtoids+") and rownum=1),0) as readCount");
			 	else
			 		sppb.setOutfields("b.doccontent, ifnull((select sum(readcount) from docReadTag where userType ="+user.getLogintype()+" and docid=r.id and userid in("+belongtoids+") limit 1),0) as readCount");
			 		
			}else{
				if(isoracle)
					sppb.setOutfields("b.doccontent, nvl((select readcount from docReadTag where userType ="+user.getLogintype()+" and docid=r.id and userid="+user.getUID()+" and rownum=1),0) as readCount");
				else
					sppb.setOutfields("b.doccontent, ifnull((select readcount from docReadTag where userType ="+user.getLogintype()+" and docid=r.id and userid="+user.getUID()+" limit 1),0) as readCount");
			}
            sppb.setBackFields("t1.id,t1.docsubject,t1.doccreaterid,t1.istop,t1.topdate,t1.toptime,t1.doccreatedate,t1.doccreatetime,t1.doclastmoddate,t1.doclastmodtime,t1.usertype");
            sppb.setSqlFrom(" DocDetail t1, "
                    + ShareManager.getShareDetailTableByUserNew("doc", user) + " t2 ");
            sppb.setSqlWhere(" where "
                    + "t1.id=t2.sourceid " + newsclause  +this.getDateDuringSql(this.getDateDuringForHp()));
            sppb.setOutsqlform("DocDetailContent b");
            
            sppb.setOutsqlwhere("where b.docid=r.id");
            sppb.setDistinct(true);            
            sppb.setPrimaryKey("t1.id");
            //sppb.setSqlOrderBy("a.istop,a.topdate,a.toptime,a.doclastmoddate,a.doclastmodtime");
            sppb.setSqlOrderBy("(case when t1.istop is null then 0 else t1.istop end),(case when t1.topdate is null or t1.istop is null then '1900-01-01' else t1.topdate end),(case when t1.toptime is null or t1.istop is null then '00:00:00' else t1.toptime end),t1.doclastmoddate,t1.doclastmodtime");
            sppb.setSortWay(sppb.DESC);
        } else {
            //sppb.setBackFields("id,docsubject,doccontent,doclastmoddate,doclastmodtime,doccreaterid,usertype");
            //sppb.setSqlFrom("from DocDetail");
            //sppb.setSqlWhere(" where id in (select distinct t1.id from DocDetail  t1, "
            //        + ShareManager.getShareDetailTableByUserNew("doc", user) + " t2 where " + "t1.id=t2.sourceid"
            //        + newsclause + ")");

            //sppb.setPrimaryKey("id");
            //sppb.setSqlOrderBy("istop,topdate,toptime,doclastmoddate,doclastmodtime");
            //sppb.setSortWay(sppb.DESC);
            
        	sppb.setBackFields("id,istop,topdate,toptime,doclastmoddate,doclastmodtime");
			if(belongtoshow.equals("1")&&account_type.equals("0")&&!belongtoids.equals("")){
			 belongtoids+=","+user.getUID();
             sppb.setOutfields("a.id,a.docsubject,a.doccontent,a.doclastmoddate,a.doclastmodtime,a.doccreaterid,a.usertype, isnull((select sum(readcount) from docReadTag where userType ="+user.getLogintype()+" and docid=a.id and userid in("+belongtoids+") ),0) as readCount");
			}else{
			 sppb.setOutfields("a.id,a.docsubject,a.doccontent,a.doclastmoddate,a.doclastmodtime,a.doccreaterid,a.usertype, isnull((select top 1 readcount from docReadTag where userType ="+user.getLogintype()+" and docid=a.id and userid="+user.getUID()+"),0) as readCount");
			}
            sppb.setSqlFrom("from DocDetail  t1, "
                    + ShareManager.getShareDetailTableByUserNew("doc", user) + " t2");
            sppb.setOutsqlform("DocDetail  a");
            sppb.setSqlWhere(" where " + "t1.id=t2.sourceid"+ newsclause +this.getDateDuringSql(this.getDateDuringForHp()));
            sppb.setOutsqlwhere("where a.id=r.id");

            sppb.setDistinct(true);
            sppb.setPrimaryKey("id");
            sppb.setSqlOrderBy("istop,topdate,toptime,doclastmoddate,doclastmodtime");
            sppb.setSortWay(sppb.DESC);
        }
        if(pagenum==1) spu.setRecordCount(perpage);
        spu.setSpp(sppb);
        rsSql = spu.getCurrentPageRs(pagenum, perpage);
        rs = rsSql.getData();
    }
    
    /**
     * 选择文档信息
     * 
     * @param newsclause sql条件
     * @param user user对象
     * @throws Exception
     */
    public void selectNewsDocInfo4Synergy(String newsfrom,String newsclause, User user, int perpage, int pagenum) throws Exception {
        RecordSet rsSQL = new RecordSet();
        String dbtype = rsSQL.getDBType();
        boolean isoracle = dbtype.equals(DBConstant.DB_TYPE_ORACLE);
        boolean ismysql = dbtype.equals(DBConstant.DB_TYPE_MYSQL);
        SplitPageParaBean sppb = new SplitPageParaBean();
        SplitPageUtil spu = new SplitPageUtil();
	    String belongtoshow = userSetting.getBelongtoshowByUserId(user.getUID()+""); 
	    String belongtoids =  user.getBelongtoids();
	    String account_type = user.getAccount_type();
        if (isoracle || ismysql) { // oralce

            //sppb .setBackFields("a.id,a.docsubject,b.doccontent,a.doclastmoddate,a.doclastmodtime,a.doccreaterid, a.usertype,a.doccreatedate,a.doccreatetime");
           if(belongtoshow.equals("1")&&account_type.equals("0")&&!belongtoids.equals("")){
		    belongtoids+=","+user.getUID();
		    	if(isoracle)
		    		sppb.setOutfields("b.doccontent, nvl((select sum(readcount) from docReadTag where userType ="+user.getLogintype()+" and docid=r.id and userid in("+belongtoids+") and rownum=1),0) as readCount");
		    	else
		    		sppb.setOutfields("b.doccontent, ifnull((select sum(readcount) from docReadTag where userType ="+user.getLogintype()+" and docid=r.id and userid in("+belongtoids+") limit 1),0) as readCount");
		    		
		   }else{
			   if(isoracle)
				   sppb.setOutfields("b.doccontent, nvl((select readcount from docReadTag where userType ="+user.getLogintype()+" and docid=r.id and userid="+user.getUID()+" and rownum=1),0) as readCount");
			   else
				   sppb.setOutfields("b.doccontent, ifnull((select readcount from docReadTag where userType ="+user.getLogintype()+" and docid=r.id and userid="+user.getUID()+" limit 1),0) as readCount");
		   }
			sppb.setBackFields("t1.id,t1.docsubject,t1.doccreaterid,t1.istop,t1.topdate,t1.toptime,t1.doccreatedate,t1.doccreatetime,t1.doclastmoddate,t1.doclastmodtime,t1.usertype");
            sppb.setSqlFrom(" DocDetail t1, "
                    + ShareManager.getShareDetailTableByUserNew("doc", user) + " t2 ");
            sppb.setSqlWhere(" where "+ "t1.id=t2.sourceid " + newsclause  +this.getDateDuringSql(this.getDateDuringForHp()));
            sppb.setOutsqlform("DocDetailContent b");
            
            sppb.setOutsqlwhere("where b.docid=r.id");
            sppb.setDistinct(true);            
            sppb.setPrimaryKey("t1.id");
            //sppb.setSqlOrderBy("a.istop,a.topdate,a.toptime,a.doclastmoddate,a.doclastmodtime");
            sppb.setSqlOrderBy("(case when t1.istop is null then 0 else t1.istop end),(case when t1.topdate is null or t1.istop is null then '1900-01-01' else t1.topdate end),(case when t1.toptime is null or t1.istop is null then '00:00:00' else t1.toptime end),t1.doclastmoddate,t1.doclastmodtime");
            sppb.setSortWay(sppb.DESC);
        } else {
            //sppb.setBackFields("id,docsubject,doccontent,doclastmoddate,doclastmodtime,doccreaterid,usertype");
            //sppb.setSqlFrom("from DocDetail");
            //sppb.setSqlWhere(" where id in (select distinct t1.id from DocDetail  t1, "
            //        + ShareManager.getShareDetailTableByUserNew("doc", user) + " t2 where " + "t1.id=t2.sourceid"
            //        + newsclause + ")");

            //sppb.setPrimaryKey("id");
            //sppb.setSqlOrderBy("istop,topdate,toptime,doclastmoddate,doclastmodtime");
            //sppb.setSortWay(sppb.DESC);
            
        	sppb.setBackFields("t1.id,istop,topdate,toptime,doclastmoddate,doclastmodtime");
			if(belongtoshow.equals("1")&&account_type.equals("0")&&!belongtoids.equals("")){
		    belongtoids+=","+user.getUID();
            sppb.setOutfields("a.id,a.docsubject,a.doccontent,a.doclastmoddate,a.doclastmodtime,a.doccreaterid,a.usertype, isnull((select sum(readcount) from docReadTag where userType ="+user.getLogintype()+" and docid=a.id and userid in("+belongtoids+") ),0) as readCount");
            }else{
			sppb.setOutfields("a.id,a.docsubject,a.doccontent,a.doclastmoddate,a.doclastmodtime,a.doccreaterid,a.usertype, isnull((select top 1 readcount from docReadTag where userType ="+user.getLogintype()+" and docid=a.id and userid="+user.getUID()+"),0) as readCount");
			}
			String sqlfrom = "from DocDetail  t1, "
                + ShareManager.getShareDetailTableByUserNew("doc", user) + " t2";
            if(!newsfrom.equals(""))
            	sqlfrom += newsfrom;
            sppb.setSqlFrom(sqlfrom);
            sppb.setOutsqlform("DocDetail  a");
            String sqlwhere = " where " + "t1.id=t2.sourceid"+ newsclause +this.getDateDuringSql(this.getDateDuringForHp());
            if(!newsfrom.equals(""))
            	sqlwhere += " and t3.scope = 'DocCustomFieldBySecCategory' and t1.id = t3.id ";
            sppb.setSqlWhere(sqlwhere);
            sppb.setOutsqlwhere("where a.id=r.id");

            sppb.setDistinct(true);
            sppb.setPrimaryKey("id");
            sppb.setSqlOrderBy("istop,topdate,toptime,doclastmoddate,doclastmodtime");
            sppb.setSortWay(sppb.DESC);
        }
        if(pagenum==1) spu.setRecordCount(perpage);
        spu.setSpp(sppb);
        rsSQL = spu.getCurrentPageRs(pagenum, perpage);
        
        rs = rsSQL.getData();
    }

    /**
     * 选择文档信息(带有虚拟目录的)
     * 
     * @param newsclause sql条件
     * @param user user对象
     * @throws Exception
     */
    public void selectNewsDocInfo(String newsclause, User user, int perpage, int pagenum,String dummyids) throws Exception {
    	if(",".equals(dummyids.substring(0,1))) dummyids=dummyids.substring(1);
    		
    	RecordSet rsSql = new RecordSet();
    	String dbtype = rsSql.getDBType();
        boolean isoracle = dbtype.equals(DBConstant.DB_TYPE_ORACLE);
        boolean ismysql = dbtype.equals(DBConstant.DB_TYPE_MYSQL);
        SplitPageParaBean sppb = new SplitPageParaBean(); 
        SplitPageUtil spu = new SplitPageUtil();
        if (isoracle || ismysql) { // oralce        	
            sppb
                    .setBackFields("a.id,a.docsubject,b.doccontent,a.doclastmoddate,a.doclastmodtime,a.doccreaterid, a.usertype,a.doccreatedate,a.doccreatetime");
            sppb.setSqlFrom("from DocDetail a, DocDetailContent b");
            sppb.setSqlWhere(" where a.id in (select distinct t1.id from DocDetail t1, "
                    + ShareManager.getShareDetailTableByUser("doc", user) + " t2,DocDummyDetail  t3 where "
                    + "t1.id=t2.sourceid and t1.id = t3.docid and t3.catelogid in("+dummyids+") " + newsclause + this.getDateDuringSql(this.getDateDuringForHp())+")  and a.id=b.docid");
            sppb.setPrimaryKey("a.id");
            sppb.setSqlOrderBy("(case when a.istop is null then 0 else a.istop end),(case when a.topdate is null or a.istop is null then '1900-01-01' else a.topdate end),(case when a.toptime is null or a.istop is null then '00:00:00' else a.toptime end),a.doclastmoddate,a.doclastmodtime");
            sppb.setSortWay(sppb.DESC);
        } else {
            sppb.setBackFields("id,docsubject,doccontent,doclastmoddate,doclastmodtime,doccreaterid,usertype");
            sppb.setSqlFrom("from DocDetail");
            sppb.setSqlWhere(" where id in (select distinct t1.id from DocDetail  t1, "
                    + ShareManager.getShareDetailTableByUser("doc", user) + " t2,DocDummyDetail  t3 where  t1.id=t2.sourceid  and t1.id=t3.docid and t3.catelogid in("+dummyids+") "
                    + newsclause + this.getDateDuringSql(this.getDateDuringForHp())+")");

            sppb.setPrimaryKey("id");
            sppb.setSqlOrderBy("istop,topdate,toptime,doclastmoddate,doclastmodtime");
            sppb.setSortWay(sppb.DESC);
        }
        if(pagenum==1) spu.setRecordCount(perpage);
        spu.setSpp(sppb);
        rsSql = spu.getCurrentPageRs(pagenum, perpage);
        
        rs = rsSql.getData();
    }
    /**
     * 选择文档信息(带有虚拟目录的)
     * 
     * @param newsclause sql条件
     * @param user user对象
     * @throws Exception
     */
    public void selectNewsDocInfoForHp(String newsclause, User user, int perpage, int pagenum,String dummyids) throws Exception {
    	if(",".equals(dummyids.substring(0,1))) dummyids=dummyids.substring(1);
    		
    	RecordSet rsSql = new RecordSet();
    	String dbtype = rsSql.getDBType();
        boolean isoracle = dbtype.equals(DBConstant.DB_TYPE_ORACLE);
        boolean ismysql = dbtype.equals(DBConstant.DB_TYPE_MYSQL);
        SplitPageParaBean sppb = new SplitPageParaBean(); 
        SplitPageUtil spu = new SplitPageUtil();
		String belongtoshow = userSetting.getBelongtoshowByUserId(user.getUID()+""); 
	    String belongtoids =  user.getBelongtoids();
	    String account_type = user.getAccount_type();
        if (isoracle || ismysql) { // oralce
        	//sppb.setOutfields("b.doccontent, nvl((select readcount from docReadTag where userType ="+user.getLogintype()+" and docid=a.id and userid="+user.getUID()+" and rownum=1),0) as readCount");
        	if(belongtoshow.equals("1")&&account_type.equals("0")&&!belongtoids.equals("")){
			 belongtoids+=","+user.getUID();
			 	if(isoracle)
			 		sppb.setOutfields("b.doccontent, nvl((select sum(readcount) from docReadTag where userType ="+user.getLogintype()+" and docid=r.id and userid in("+belongtoids+") and rownum=1),0) as readCount");
			 	else
			 		sppb.setOutfields("b.doccontent, ifnull((select sum(readcount) from docReadTag where userType ="+user.getLogintype()+" and docid=r.id and userid in("+belongtoids+") limit 1),0) as readCount");
			}else{
				if(isoracle)
					sppb.setOutfields("b.doccontent, nvl((select readcount from docReadTag where userType ="+user.getLogintype()+" and docid=r.id and userid="+user.getUID()+" and rownum=1),0) as readCount");
				else
					sppb.setOutfields("b.doccontent, ifnull((select readcount from docReadTag where userType ="+user.getLogintype()+" and docid=r.id and userid="+user.getUID()+" limit 1),0) as readCount");
			}
        	sppb.setDistinct(true);        	
            sppb.setBackFields(" t1.istop,t1.topdate,t1.toptime,t1.id,t1.docsubject,t1.doclastmoddate,t1.doclastmodtime,t1.doccreaterid, t1.usertype,t1.doccreatedate,t1.doccreatetime");
            sppb.setSqlFrom("from DocDetail t1, "
                    + ShareManager.getShareDetailTableByUser("doc", user) + " t2,DocDummyDetail  t3");
            sppb.setOutsqlform("DocDetailContent  b");
            sppb.setSqlWhere(" where "
                    + "t1.id=t2.sourceid and t1.id = t3.docid and t3.catelogid in("+dummyids+") " + newsclause + this.getDateDuringSql(this.getDateDuringForHp()) );
            sppb.setOutsqlwhere("where b.docid=r.id");
            sppb.setPrimaryKey("t1.id");
            sppb.setSqlOrderBy("(case when t1.istop is null then 0 else t1.istop end),(case when t1.topdate is null or t1.istop is null then '1900-01-01' else t1.topdate end),(case when t1.toptime is null or t1.istop is null then '00:00:00' else t1.toptime end),t1.doclastmoddate,t1.doclastmodtime");
            sppb.setSortWay(sppb.DESC);
        } else {
			if(belongtoshow.equals("1")&&account_type.equals("0")&&!belongtoids.equals("")){
			 belongtoids+=","+user.getUID();
            sppb.setOutfields("a.id,a.docsubject,a.doccontent,a.doclastmoddate,a.doclastmodtime,a.doccreaterid,a.usertype, isnull((select sum(readcount) from docReadTag where userType ="+user.getLogintype()+" and docid=a.id and userid in("+belongtoids+") ),0) as readCount");
			}else{
			sppb.setOutfields("a.id,a.docsubject,a.doccontent,a.doclastmoddate,a.doclastmodtime,a.doccreaterid,a.usertype, isnull((select top 1 readcount from docReadTag where userType ="+user.getLogintype()+" and docid=a.id and userid="+user.getUID()+"),0) as readCount");
			}
            
            sppb.setBackFields("t1.id,t1.doclastmoddate,t1.doclastmodtime,t1.istop,t1.topdate,t1.toptime");
            sppb.setSqlFrom("from DocDetail  t1, "
                    + ShareManager.getShareDetailTableByUserNew("doc", user) + " t2,DocDummyDetail  t3 ");
            sppb.setOutsqlform("DocDetail  a");
            sppb.setSqlWhere("where  t1.id=t2.sourceid  and t1.id=t3.docid and t3.catelogid in("+dummyids+") "+ newsclause+this.getDateDuringSql(this.getDateDuringForHp()) );
            sppb.setOutsqlwhere("where a.id=r.id");
            sppb.setPrimaryKey("t1.id");
            sppb.setDistinct(true);
            sppb.setSqlOrderBy("istop,topdate,toptime,doclastmoddate,doclastmodtime");
            sppb.setSortWay(sppb.DESC);
        }
        if(pagenum==1) spu.setRecordCount(perpage);
        spu.setSpp(sppb);
        rsSql = spu.getCurrentPageRs(pagenum, perpage);
        rs = rsSql.getData();
    }
    
    /**
     * 选择文档信息(带有虚拟目录的)
     * 
     * @param newsclause sql条件
     * @param user user对象
     * @throws Exception
     */
    public void selectNewsDocInfoForHpSynergy(String newsfrom, String newsclause, User user, int perpage, int pagenum,String dummyids) throws Exception {
    	if(",".equals(dummyids.substring(0,1))) dummyids=dummyids.substring(1);
    		
    	RecordSet rsSql = new RecordSet();
    	String dbtype = rsSql.getDBType();
        boolean isoracle = dbtype.equals(DBConstant.DB_TYPE_ORACLE);
        boolean ismysql = dbtype.equals(DBConstant.DB_TYPE_MYSQL);
        SplitPageParaBean sppb = new SplitPageParaBean(); 
        SplitPageUtil spu = new SplitPageUtil();
		String belongtoshow = userSetting.getBelongtoshowByUserId(user.getUID()+""); 
	    String belongtoids =  user.getBelongtoids();
	    String account_type = user.getAccount_type();
        if (isoracle || ismysql) { // oralce
        	//sppb.setOutfields("b.doccontent, nvl((select readcount from docReadTag where userType ="+user.getLogintype()+" and docid=a.id and userid="+user.getUID()+" and rownum=1),0) as readCount");
        	if(belongtoshow.equals("1")&&account_type.equals("0")&&!belongtoids.equals("")){
			 belongtoids+=","+user.getUID();
			 	if(isoracle)
			 		sppb.setOutfields("b.doccontent, nvl((select sum(readcount) from docReadTag where userType ="+user.getLogintype()+" and docid=r.id and userid in("+belongtoids+") and rownum=1),0) as readCount");
			 	else
			 		sppb.setOutfields("b.doccontent, ifnull((select sum(readcount) from docReadTag where userType ="+user.getLogintype()+" and docid=r.id and userid in("+belongtoids+") limit 1),0) as readCount");
			}else{
				if(isoracle)
					sppb.setOutfields("b.doccontent, nvl((select readcount from docReadTag where userType ="+user.getLogintype()+" and docid=r.id and userid="+user.getUID()+" and rownum=1),0) as readCount");
				else
					sppb.setOutfields("b.doccontent, ifnull((select readcount from docReadTag where userType ="+user.getLogintype()+" and docid=r.id and userid="+user.getUID()+" limit 1),0) as readCount");
			}
        	        	
            sppb.setBackFields("t1.id,t1.docsubject,t1.doclastmoddate,t1.doclastmodtime,t1.doccreaterid, t1.usertype,t1.doccreatedate,t1.doccreatetime");
            sppb.setSqlFrom("from DocDetail t1, "
                    + ShareManager.getShareDetailTableByUser("doc", user) + " t2,DocDummyDetail  t3");
            sppb.setOutsqlform("DocDetailContent  b");
            sppb.setSqlWhere(" where "
                    + "t1.id=t2.sourceid and t1.id = t3.docid and t3.catelogid in("+dummyids+") " + newsclause + this.getDateDuringSql(this.getDateDuringForHp()) );
            sppb.setOutsqlwhere("where b.docid=r.id");
            sppb.setPrimaryKey("t1.id");
            sppb.setSqlOrderBy("(case when t1.istop is null then 0 else t1.istop end),(case when t1.topdate is null or t1.istop is null then '1900-01-01' else t1.topdate end),(case when t1.toptime is null or t1.istop is null then '00:00:00' else t1.toptime end),t1.doclastmoddate,t1.doclastmodtime");
            sppb.setSortWay(sppb.DESC);
        } else {
			if(belongtoshow.equals("1")&&account_type.equals("0")&&!belongtoids.equals("")){
			 belongtoids+=","+user.getUID();
            sppb.setOutfields("a.id,a.docsubject,a.doccontent,a.doclastmoddate,a.doclastmodtime,a.doccreaterid,a.usertype, isnull((select sum(readcount) from docReadTag where userType ="+user.getLogintype()+" and docid=a.id and userid in("+belongtoids+") ),0) as readCount");
			}else{
			sppb.setOutfields("a.id,a.docsubject,a.doccontent,a.doclastmoddate,a.doclastmodtime,a.doccreaterid,a.usertype, isnull((select top 1 readcount from docReadTag where userType ="+user.getLogintype()+" and docid=a.id and userid="+user.getUID()+"),0) as readCount");
			}
            
            sppb.setBackFields("t1.id,t1.doclastmoddate,t1.doclastmodtime,t1.istop,t1.topdate,t1.toptime");
            sppb.setSqlFrom("from DocDetail  t1, "
                    + ShareManager.getShareDetailTableByUserNew("doc", user) + " t2,DocDummyDetail  t3 ");
            sppb.setOutsqlform("DocDetail  a");
            sppb.setSqlWhere("where  t1.id=t2.sourceid  and t1.id=t3.docid and t3.catelogid in("+dummyids+") "+ newsclause+this.getDateDuringSql(this.getDateDuringForHp()) );
            sppb.setOutsqlwhere("where a.id=r.id");
            sppb.setPrimaryKey("t1.id");
            sppb.setDistinct(true);
            sppb.setSqlOrderBy("istop,topdate,toptime,doclastmoddate,doclastmodtime");
            sppb.setSortWay(sppb.DESC);
        }
        if(pagenum==1) spu.setRecordCount(perpage);
        spu.setSpp(sppb);
        rsSql = spu.getCurrentPageRs(pagenum, perpage);
        rs = rsSql.getData();
    }
    
    /**
     * 选择文档信息
     * 
     * @throws Exception
     */
    public void selectDocInfo() throws Exception {
        RecordSet rsSql = new RecordSet();
        String dbtype = rsSql.getDBType();
        boolean isoracle = dbtype.equals(DBConstant.DB_TYPE_ORACLE);
        boolean ismysql = dbtype.equals(DBConstant.DB_TYPE_MYSQL);

        String sql = "";
        // TD2401 外部新闻页显示出现异常。
        if (!"and".equalsIgnoreCase(sql_where.substring(0, 4).trim()))
            sql_where = " and " + sql_where;
        if (isoracle || ismysql) {
            sql = "select t1.* , t2.doccontent from DocDetail t1 , DocDetailContent t2  where t1.id = t2.docid "
                    + sql_where + " order by doclastmoddate desc, doclastmodtime desc";
        } else
            sql = "select * from DocDetail where id<>0 " + sql_where + " order by doclastmoddate desc, doclastmodtime desc";

        rsSql.executeSql(sql);
        rs = rsSql.getData();
    }
    /**
     * 获取文档最新版本content字段
     * @param docid
     * @param ischeck
     * @return
     */
    public String getNewDocid(String docid,boolean ischeck)
    {
    	String sDoceditionid="-1";
    	String doccontent = "";
    	if("".equals(docid)) return "";
    	RecordSet rs= new RecordSet();
    	rs.executeSql("select doceditionid,doccontent from docdetail where id="+docid);
    	if(rs.next())
    	{
    		sDoceditionid=Util.null2String(rs.getString("doceditionid"));
    		doccontent=Util.null2String(rs.getString("doccontent"));
    	}
        if("-1".equals(sDoceditionid) || "".equals(sDoceditionid)) return doccontent;
        rs.executeSql("select id,doccontent from docdetail where docedition=(select max(docedition) from docdetail where doceditionid="+sDoceditionid+") " +
        		"and doceditionid="+sDoceditionid);
        
        if(rs.next())
        {
        	doccontent=Util.null2String(rs.getString("doccontent"));
        }
          
    	return doccontent;    	
    }
    /**
     * 移到下一条记录并判断是否还有下一条记录
     * 
     * @return 判断是否还有下一条记录
     * @throws Exception
     */
    public boolean next() throws Exception {
        return rs.next();
    }

    /**
     * 选择出来的得到文档总数
     * 
     * @return 选择出来的文档总数
     * @throws Exception
     */
    public int getCount() throws Exception {
        return rs.getCounts();
    }

    /**
     * 关闭连结
     */
    public void closeStatement() {
        try {
           // statement.close();
        } catch (Exception ex) {
        }
    }

    /**
     * 通过文档ID得到相应的文档信息
     * 
     * @throws Exception
     */
    public void getDocInfoById() throws Exception {

        RecordSet rsSql = new RecordSet();
        String dbtype = rsSql.getDBType();
        boolean isoracle = dbtype.equals(DBConstant.DB_TYPE_ORACLE);
        boolean ismysql = dbtype.equals(DBConstant.DB_TYPE_MYSQL);

        String sql = "";

        if (isoracle || ismysql) {
            sql = "select t1.* , t2.doccontent from DocDetail t1 , DocDetailContent t2 where t1.id = t2.docid and id = "
                    + id;
        } else
            sql = "select * from DocDetail where id = " + id;

        rsSql.executeSql(sql);
        rs = rsSql.getData();
        rs.next();
    }

    /**
     * 添加一个文档
     * 
     * @throws Exception
     */
    public void AddDocInfo() throws Exception {

        String sql = "";
        RecordSet statement = new RecordSet();
        boolean isoracle = (statement.getDBType()).equals("oracle");
		if(this.doccontent.contains("/FCKEditor/FlashVideo.jpg")){
		 doccontent+="<script>initFlashVideo();</script>";
		 
		}
        if (isoracle ||(statement.getDBType()).equals("mysql")) {

            sql = "insert into DocDetail(" +
                  "id,maincategory,subcategory,seccategory,doclangurage," +
                  "docapprovable,docreplyable,isreply,replydocid,docsubject," +
                  "docpublishtype,itemid,itemmaincategoryid,hrmresid,crmid," +
                  "projectid,financeid,doccreaterid,docdepartmentid,doccreatedate," +
                  "doccreatetime,doclastmoduserid,doclastmoddate,doclastmodtime,docapproveuserid," +
                  "docapprovedate,docapprovetime,docarchiveuserid,docarchivedate,docarchivetime," +
                  "docstatus,parentids,assetid,ownerid,keyword," +
                  "accessorycount,replaydoccount,usertype,doctype,cancopy," +
                  "canremind,orderable,docextendname" +
                  
                  ",doccode,docedition,doceditionid,ishistory,approveType,maindoc," +
                  "readoptercanprint,docvaliduserid,docvaliddate,docvalidtime,invalidationdate" +
                  
                  ",docCreaterType,docLastModUserType,docApproveUserType,docValidUserType,docInvalUserType" +
                  ",docArchiveUserType,docCancelUserType,docPubUserType,docReopenUserType,ownerType" +                
                  ",canPrintedNum,editMouldId" +                
                  ",secretLevel" +
                  ",replyremind" +
                  ",secretValidity" +

                  ") values(" +
                  "?,?,?,?,?,?,?,?,?,?," +
                  "?,?,?,?,?,?,?,?,?,?," +
                  "?,?,?,?,?,?,?,?,?,?," +
                  "?,?,?,?,?,?,?,?,?,?," +
                  "?,?,?" +
                  
                  ",?,?,?,?,?,?" +
                  ",?,?,?,?,?" + 
                  
                  ",?,?,?,?,?" +
                  ",?,?,?,?,?" +                  
                  ",?,?" +                  
                  ",?" +
                  ",?" +
                  ",?" +

                  ")";

            try {



                statement.executeUpdate(sql
	                , this.id
	                , this.maincategory
	                , this.subcategory
	                , this.seccategory
	                , this.doclangurage
	                , this.docapprovable
	                , this.docreplyable
	                , this.isreply
	                , this.replydocid
	                , this.docsubject
	                , this.docpublishtype
	                , this.itemid
	                , this.itemmaincategoryid
	                , this.hrmresid
	                , this.crmid
	                , this.projectid
	                , this.financeid
	                , this.doccreaterid
	                , this.docdepartmentid
	                , this.doccreatedate
	                , this.doccreatetime
	                , this.doclastmoduserid
	                , this.doclastmoddate
	                , this.doclastmodtime
	                , this.docapproveuserid
	                , this.docapprovedate
	                , this.docapprovetime
	                , this.docarchiveuserid
	                , this.docarchivedate
	                , this.docarchivetime
	                , this.docstatus
	                , this.parentids
	
	
	                , this.assetid
	                , this.ownerid
	                , this.keyword
	                , this.accessorycount
	                , this.replaydoccount
	                //38, this.usertype
	                , this.docCreaterType              
	
	
	                , this.docType
	                , this.canCopy
	                , this.canRemind
	                , this.orderable
	                , this.docextendname                
	                , this.docCode
	
	                , this.docEdition
	                , this.docEditionId
	                , this.isHistory
	                , this.approveType             
	                , this.mainDoc
	                , this.readOpterCanPrint
	                , this.docValidUserId
	
	                , this.docValidDate
	                , this.docValidTime
	
	                , this.invalidationDate
	                
	                , this.docCreaterType               
	                , this.docLastModUserType               
	                , this.docApproveUserType               
	                , this.docValidUserType               
	                , this.docInvalUserType               
	                , this.docArchiveUserType               
	                , this.docCancelUserType               
	                , this.docPubUserType               
	                , this.docReopenUserType 
	                , this.ownerType                
	                , this.canPrintedNum
	                , this.editMouldId
	                , this.secretLevel
	                , this.replyremind
	                , this.secretValidity
	               );
                // 执行触发器docdetail_getpinyin
                DocTriggerUtils docTriggerUtils = new DocTriggerUtils();
                docTriggerUtils.docdetail_getpinyin(new RecordSet());
                
            	 sql = "insert into DocDetailContent (docid, doccontent) values(?,?) ";
                 statement.executeUpdate(sql,this.id,this.doccontent);
               
                log.resetParameter();
                log.setDocId(this.id);
                log.setDocSubject(this.docsubject);
                log.setOperateType("1");
                log.setOperateUserid(userid);
                log.setUsertype(this.usertype);
                //log.setCreatertype(this.usertype);
                log.setClientAddress(this.clientip);
                log.setDocCreater(this.doccreaterid);
                log.setCreatertype(this.docCreaterType);
                log.setDocLogInfo();

            } catch (Exception e) {
                writeLog(e);
                throw e;
            } finally {
            }

        } else {

            sql = "insert into DocDetail(" +
                    "id,maincategory,subcategory,seccategory,doclangurage," +
                    "docapprovable,docreplyable,isreply,replydocid,docsubject," +
                    "doccontent,docpublishtype,itemid,itemmaincategoryid,hrmresid," +
                    "crmid,projectid,financeid,doccreaterid,docdepartmentid," +
                    "doccreatedate,doccreatetime,doclastmoduserid,doclastmoddate,doclastmodtime," +
                    "docapproveuserid,docapprovedate,docapprovetime,docarchiveuserid,docarchivedate," +
                    "docarchivetime,docstatus,parentids,assetid,ownerid," +
                    "keyword,accessorycount,replaydoccount,usertype,doctype," +
                    "cancopy,canremind,orderable,docextendname" +
                    
                    ",doccode,docedition,doceditionid,ishistory,approveType,maindoc," +
                    "readoptercanprint,docvaliduserid,docvaliddate,docvalidtime,invalidationdate" +

                    ",docCreaterType,docLastModUserType,docApproveUserType,docValidUserType,docInvalUserType" +
                    ",docArchiveUserType,docCancelUserType,docPubUserType,docReopenUserType,ownerType" +                       
                    ",canPrintedNum,editMouldId" +                       
                    ",secretLevel" +
                    ",replyremind" +
                    ",secretValidity" +
                    ") values(" +
                    "?,?,?,?,?,?,?,?,?,?," +
                    "?,?,?,?,?,?,?,?,?,?," +
                    "?,?,?,?,?,?,?,?,?,?," +
                    "?,?,?,?,?,?,?,?,?,?," +
                    "?,?,?,?" +

                    ",?,?,?,?,?,?" +
                    ",?,?,?,?,?" + 
                    
                    ",?,?,?,?,?" +
                    ",?,?,?,?,?" +                    
                    ",?,?" +                    
                    ",?" +
                    ",?" +
                    ",?" +

                    ")";

            try {

                statement.executeUpdate(sql
                , this.id
                , this.maincategory
                , this.subcategory
                , this.seccategory
                , this.doclangurage
                , this.docapprovable
                , this.docreplyable
                , this.isreply
                , this.replydocid
                , this.docsubject
                , this.doccontent
                , this.docpublishtype
                , this.itemid
                , this.itemmaincategoryid
                , this.hrmresid
                , this.crmid
                , this.projectid
                , this.financeid
                , this.doccreaterid
                , this.docdepartmentid
                , this.doccreatedate
                , this.doccreatetime
                , this.doclastmoduserid
                , this.doclastmoddate
                , this.doclastmodtime
                , this.docapproveuserid
                , this.docapprovedate
                , this.docapprovetime
                , this.docarchiveuserid
                , this.docarchivedate
                , this.docarchivetime
                , this.docstatus
                , this.parentids
                , this.assetid
                , this.ownerid
                , this.keyword
                , this.accessorycount
                , this.replaydoccount
                //39, this.usertype
                , this.docCreaterType               
                , this.docType
                , this.canCopy
                , this.canRemind
                , this.orderable
                , this.docextendname
                
                , this.docCode
                , this.docEdition
                , this.docEditionId
                , this.isHistory
                , this.approveType
                
                , this.mainDoc
                , this.readOpterCanPrint
                , this.docValidUserId
                , this.docValidDate
                , this.docValidTime
                
                , this.invalidationDate
                
                , this.docCreaterType               
                , this.docLastModUserType               
                , this.docApproveUserType               
                , this.docValidUserType               
                , this.docInvalUserType               
                , this.docArchiveUserType               
                , this.docCancelUserType               
                , this.docPubUserType               
                , this.docReopenUserType 
                , this.ownerType                
                , this.canPrintedNum                
                , this.editMouldId
                , this.secretLevel
                , this.replyremind
                , this.secretValidity
                );


                // 执行触发器docdetail_getpinyin
                DocTriggerUtils docTriggerUtils = new DocTriggerUtils();
                docTriggerUtils.docdetail_getpinyin(new RecordSet());
                log.resetParameter();
                log.setDocId(this.id);
                log.setDocSubject(this.docsubject);
                log.setOperateType("1");
                log.setOperateUserid(userid);
                log.setUsertype(this.usertype);
                log.setCreatertype(this.usertype);
                log.setClientAddress(this.clientip);
                log.setDocCreater(this.doccreaterid);
                log.setCreatertype(this.docCreaterType);
                
                log.setDocLogInfo();

            } catch (Exception e) {
                writeLog(e);
                throw e;
            } finally {
            }
        }
		RecordSet rsDummyDoc=new RecordSet();
		if (isreply.equals("1")) {
			String realReplyDocId = "";
            if (parentids != null) {
                String tempStrs[] = Util.TokenizerString2(parentids, ",");
                if (tempStrs.length >= 2)
                    realReplyDocId = tempStrs[tempStrs.length - 2];
            }
	            
			DocTreeDocFieldManager dtdfm=new DocTreeDocFieldManager();
			this.dummycata=dtdfm.getDummyStr(Util.getIntValue(realReplyDocId));
		}
		if(this.dummycata!=null && !"".equals(dummycata)){
			ArrayList dummyCataList=Util.TokenizerString(dummycata,",");
			for(int i=0;i<dummyCataList.size();i++){
				String strDummy=(String)dummyCataList.get(i);
				if(!"".equals(strDummy)){
					String importdate=TimeUtil.getCurrentDateString();
					String importtime=TimeUtil.getOnlyCurrentTimeString();
					DocTreeDocFieldComInfo ddfc=new DocTreeDocFieldComInfo();
					if(!ddfc.isHaveSameOne(strDummy,""+this.id)) {
						String strSql="insert into DocDummyDetail(catelogid,docid,importdate,importtime) values ("+strDummy+","+this.id+",'"+importdate+"','"+importtime+"')";
						rsDummyDoc.executeSql(strSql);
					}
				}
			}
		}
        //附件复制到对应的相关物理路径下
        DocSaveService.copyDocFile(this.seccategory,this.id);
		//TD12549 文档创建的时候就在docreadtag表中把创建人的纪录录入，以免发生未读文档统计出错的问题 chujun
		char flag=Util.getSeparator();
		rsDummyDoc.executeProc("docReadTag_AddByUser", ""+this.id+flag+this.doccreaterid+flag+this.docCreaterType);
		if(this.docCreaterType == "" || this.docCreaterType == null){
			rsDummyDoc.execute("update docreadtag set readcount=0 where docid="+this.id+" and userid="+this.doccreaterid+" and usertype= 1 ");
		}else{
			rsDummyDoc.execute("update docreadtag set readcount=0 where docid="+this.id+" and userid="+this.doccreaterid+" and usertype="+this.docCreaterType);
		}
		rsDummyDoc.execute("update docdetail set sumReadCount=0 where id="+this.id);
    }


    /**
     * 编辑一个文档
     * 
     * @throws Exception
     */
    public void EditDocInfo() throws Exception {
        String sql = "";
        RecordSet statement = new RecordSet();

        boolean isoracle = (statement.getDBType()).equals("oracle");
		if(this.doccontent.contains("/FCKEditor/FlashVideo.jpg")){
		 doccontent+="<script>initFlashVideo();</script>";
		 
		}

		if (isoracle ||(statement.getDBType()).equals("mysql")) {

            sql = "update DocDetail set maincategory=?,subcategory=?,seccategory=?,doclangurage=?,docapprovable=?,docreplyable=?,isreply=?,replydocid=?,docsubject=?,docpublishtype=?,itemid=?,itemmaincategoryid=?,hrmresid=?,crmid=?,projectid=?,financeid=?,doccreaterid=?,docdepartmentid=?,doccreatedate=?,doccreatetime=?,doclastmoduserid=?,doclastmoddate=?,doclastmodtime=?,docapproveuserid=?,docapprovedate=?,docapprovetime=?,docarchiveuserid=?,docarchivedate=?,docarchivetime=?,docstatus=?,assetid=?,ownerid=?,keyword=?,accessorycount=accessorycount+?,replaydoccount=?,usertype=? ,cancopy=?,canremind=? " +
                    
                    ",doccode=?,docedition=?,doceditionid=?,ishistory=?,approveType=?," +
                    "maindoc=?,readoptercanprint=?,docvaliduserid=?," +
                    "docvaliddate=?,docvalidtime=?,docpubuserid=?," +
                    "docpubdate=?,docpubtime=?,docreopenuserid=?," +
                    "docreopendate=?,docreopentime=?,docinvaluserid=?," +
                    "docinvaldate=?,docinvaltime=?,doccanceluserid=?," +
                    "doccanceldate=?,doccanceltime=?" +
                    ",selectedpubmouldid=?" +
                    ",invalidationdate=?" +
 
                    ",docCreaterType=?,docLastModUserType=?,docApproveUserType=?,docValidUserType=?,docInvalUserType=?" +
                    ",docArchiveUserType=?,docCancelUserType=?,docPubUserType=?,docReopenUserType=?,ownerType=?" +                    
                    ",canPrintedNum=?,editMouldId=?" +                    
                    ",secretLevel=?" +
                    ",replyremind=?" +
                    ",secretValidity=?" +
                    " where id=?";

            try {
                statement.executeUpdate(sql
                , this.maincategory
                , this.subcategory
                , this.seccategory
                , this.doclangurage
                , this.docapprovable
                , this.docreplyable
                , this.isreply
                , this.replydocid
                , this.docsubject
                , this.docpublishtype
                , this.itemid
                , this.itemmaincategoryid
                , this.hrmresid
                , this.crmid
                , this.projectid
                , this.financeid
                , this.doccreaterid
                , this.docdepartmentid
                , this.doccreatedate
                , this.doccreatetime
                , this.doclastmoduserid
                , this.doclastmoddate
                , this.doclastmodtime
                , this.docapproveuserid
                , this.docapprovedate
                , this.docapprovetime
                , this.docarchiveuserid
                , this.docarchivedate
                , this.docarchivetime
                , this.docstatus
                , this.assetid
                , this.ownerid
                , this.keyword
                , this.accessorycount
                , this.replaydoccount
                //36, this.usertype
                , this.docCreaterType                
                , this.canCopy
                , this.canRemind
                
                , this.docCode
                , this.docEdition
                , this.docEditionId
                , this.isHistory
                , this.approveType
                
                , this.mainDoc
                , this.readOpterCanPrint
                , this.docValidUserId
                , this.docValidDate
                , this.docValidTime
                , this.docPubUserId
                , this.docPubDate
                , this.docPubTime
                , this.docReOpenUserId
                , this.docReOpenDate
                , this.docReOpenTime
                , this.docInvalUserId
                , this.docInvalDate
                , this.docInvalTime
                , this.docCancelUserId
                , this.docCancelDate
                , this.docCancelTime
                
                , this.selectedPubMouldId
                
                , this.invalidationDate
                
                , this.docCreaterType               
                , this.docLastModUserType               
                , this.docApproveUserType               
                , this.docValidUserType               
                , this.docInvalUserType               
                , this.docArchiveUserType               
                , this.docCancelUserType               
                , this.docPubUserType               
                , this.docReopenUserType 
                , this.ownerType                 

                //73, this.id
                , this.canPrintedNum
                , this.editMouldId               
                , this.secretLevel
                , this.replyremind
                , this.secretValidity
                , this.id
                );

            	 sql = "update DocDetailContent set doccontent=? where docid=? ";
                 statement.executeUpdate(sql,this.doccontent,this.id);
               
                // 执行触发器docdetail_getpinyin
                DocTriggerUtils docTriggerUtils = new DocTriggerUtils();
                docTriggerUtils.docdetail_getpinyin(this.id,new RecordSet());


                log.resetParameter();
                log.setDocId(this.id);
                log.setDocSubject(this.docsubject);
                log.setOperateType("2");
                log.setOperateUserid(userid);
                log.setUsertype(this.opreateType);
                log.setClientAddress(this.clientip);
                log.setDocCreater(this.doccreaterid);
                log.setCreatertype(this.docCreaterType);
                log.setDocLogInfo();
            } catch (Exception e) {
                writeLog(e);
                throw e;
            } finally {
            }
        } else {

            sql = "update DocDetail set maincategory=?,subcategory=?,seccategory=?,doclangurage=?,docapprovable=?,docreplyable=?,isreply=?,replydocid=?,docsubject=?,doccontent=?,docpublishtype=?,itemid=?,itemmaincategoryid=?,hrmresid=?,crmid=?,projectid=?,financeid=?,doccreaterid=?,docdepartmentid=?,doccreatedate=?,doccreatetime=?,doclastmoduserid=?,doclastmoddate=?,doclastmodtime=?,docapproveuserid=?,docapprovedate=?,docapprovetime=?,docarchiveuserid=?,docarchivedate=?,docarchivetime=?,docstatus=?,assetid=?,ownerid=?,keyword=?,accessorycount=accessorycount+?,replaydoccount=?,usertype=?,cancopy=?,canremind=?" +

            ",doccode=?,docedition=?,doceditionid=?,ishistory=?,approveType=?," +
            "maindoc=?,readoptercanprint=?,docvaliduserid=?," +
            "docvaliddate=?,docvalidtime=?,docpubuserid=?," +
            "docpubdate=?,docpubtime=?,docreopenuserid=?," +
            "docreopendate=?,docreopentime=?,docinvaluserid=?," +
            "docinvaldate=?,docinvaltime=?,doccanceluserid=?," +
            "doccanceldate=?,doccanceltime=?" +
            ",selectedpubmouldid=?" +
            ",invalidationdate=?" +
            
            ",docCreaterType=?,docLastModUserType=?,docApproveUserType=?,docValidUserType=?,docInvalUserType=?" +
            ",docArchiveUserType=?,docCancelUserType=?,docPubUserType=?,docReopenUserType=?,ownerType=?" +  
            ",canPrintedNum=?,editMouldId=?" + 
            ",secretLevel=?" +
            ",replyremind=?" +
            ",secretValidity=?" +
            " where id=?";
            
            try {
                statement.executeUpdate(sql
                , this.maincategory
                , this.subcategory
                , this.seccategory
                , this.doclangurage
                , this.docapprovable
                , this.docreplyable
                , this.isreply
                , this.replydocid
                , this.docsubject
                , this.doccontent
                , this.docpublishtype
                , this.itemid
                , this.itemmaincategoryid
                , this.hrmresid
                , this.crmid
                , this.projectid
                , this.financeid
                , this.doccreaterid
                , this.docdepartmentid
                , this.doccreatedate
                , this.doccreatetime
                , this.doclastmoduserid
                , this.doclastmoddate
                , this.doclastmodtime
                , this.docapproveuserid
                , this.docapprovedate
                , this.docapprovetime
                , this.docarchiveuserid
                , this.docarchivedate
                , this.docarchivetime
                , this.docstatus
                , this.assetid
                , this.ownerid
                , this.keyword
                , this.accessorycount
                , this.replaydoccount
                //37, this.usertype
                , this.docCreaterType              
                , this.canCopy
                , this.canRemind

                , this.docCode
                , this.docEdition
                , this.docEditionId
                , this.isHistory
                , this.approveType
                
                , this.mainDoc
                , this.readOpterCanPrint
                , this.docValidUserId
                , this.docValidDate
                , this.docValidTime
                , this.docPubUserId
                , this.docPubDate
                , this.docPubTime
                , this.docReOpenUserId
                , this.docReOpenDate
                , this.docReOpenTime
                , this.docInvalUserId
                , this.docInvalDate
                , this.docInvalTime
                , this.docCancelUserId
                , this.docCancelDate
                , this.docCancelTime
                
                , this.selectedPubMouldId

                , this.invalidationDate

                , this.docCreaterType               
                , this.docLastModUserType               
                , this.docApproveUserType               
                , this.docValidUserType               
                , this.docInvalUserType               
                , this.docArchiveUserType               
                , this.docCancelUserType               
                , this.docPubUserType               
                , this.docReopenUserType 
                , this.ownerType                
                
                //74, this.id
                , this.canPrintedNum
                , this.editMouldId
                , this.secretLevel
                , this.replyremind
                , this.secretValidity
                , this.id);

                // 执行触发器docdetail_getpinyin
                DocTriggerUtils docTriggerUtils = new DocTriggerUtils();
                docTriggerUtils.docdetail_getpinyin(this.id,new RecordSet());
                log.resetParameter();
                log.setDocId(this.id);
                log.setDocSubject(this.docsubject);
                log.setOperateType("2");
                log.setOperateUserid(userid);
                log.setUsertype(this.opreateType);
                log.setClientAddress(this.clientip);
                log.setDocCreater(this.doccreaterid);
                log.setCreatertype(this.docCreaterType);                
                log.setDocLogInfo();
            } catch (Exception e) {
                writeLog(e);
                throw e;
            } finally {
            } 
        }
        //附件复制到对应相关物理路径下
        DocSaveService.copyDocFile(this.seccategory,this.id);
//        if (isreply.equals("1")) {
//			String realReplyDocId = "";
//            if (parentids != null) {
//                String tempStrs[] = Util.TokenizerString2(parentids, ",");
//                if (tempStrs.length >= 2)
//                    realReplyDocId = tempStrs[tempStrs.length - 2];
//            }
//	            
//			DocTreeDocFieldManager dtdfm=new DocTreeDocFieldManager();
//			this.dummycata=dtdfm.getDummyStr(Util.getIntValue(realReplyDocId));
//		}
        
		RecordSet rsDummyDoc=new RecordSet();
		rsDummyDoc.executeSql("delete DocDummyDetail where docid="+this.id);
		if(this.dummycata!=null && !"".equals(dummycata)){
			ArrayList dummyCataList=Util.TokenizerString(dummycata,",");
			for(int i=0;i<dummyCataList.size();i++){
				String strDummy=(String)dummyCataList.get(i);
				if(!"".equals(strDummy)){
					String importdate=TimeUtil.getCurrentDateString();
					String importtime=TimeUtil.getOnlyCurrentTimeString();
					DocTreeDocFieldComInfo ddfc=new DocTreeDocFieldComInfo();
					if(!ddfc.isHaveSameOne(strDummy,""+this.id)) {
						String strSql="insert into DocDummyDetail(catelogid,docid,importdate,importtime) values ("+strDummy+","+this.id+",'"+importdate+"','"+importtime+"')";
						rsDummyDoc.executeSql(strSql);
					}
				}
			}
		}
    } 

    /**
     * 归档一个文档
     * 
     * @throws Exception
     */
    public void ArchiveDocInfo() throws Exception {
        String sql = "update DocDetail set docarchiveuserid=?,docarchivedate=?,docarchivetime=?,docstatus=? , docno= ? where id=?";

        RecordSet statement = new RecordSet();
        try {
           
            statement.executeUpdate(sql
            		, this.docarchiveuserid
		            , this.docarchivedate
		            , this.docarchivetime
		            , this.docstatus
		            , this.docno
		            , this.id
            		);
            log.resetParameter();
            log.setDocId(this.id);
            log.setDocSubject(this.docsubject);
            log.setOperateType("7");
            log.setOperateUserid(userid);
            log.setUsertype(this.usertype);
            log.setClientAddress(this.clientip);
            log.setDocCreater(this.doccreaterid);
            log.setDocLogInfo();
        } catch (Exception e) {
            writeLog(e);
            throw e;
        } finally {
            try {
//                statement.close();
            } catch (Exception ex) {
            }
        }
    }

    /**
     * 退回一个文档
     * 
     * @throws Exception
     */
    public void ReloadDocInfo() throws Exception {
        String sql = "update DocDetail set docarchiveuserid=?,docarchivedate=?,docarchivetime=?,docstatus=? where id=?";

        RecordSet statement = new RecordSet();
        try {

            statement.executeUpdate(sql,0,"","",docstatus,id);
            log.resetParameter();
            log.setDocId(this.id);
            log.setDocSubject(this.docsubject);
            log.setOperateType("8");
            log.setOperateUserid(userid);
            log.setUsertype(this.usertype);
            log.setClientAddress(this.clientip);
            log.setDocCreater(this.doccreaterid);
            log.setDocLogInfo();
        } catch (Exception e) {
            writeLog(e);
            throw e;
        } finally {
        }
    }

    /**
     * 退回一个文档
     * 
     * @throws Exception
     */
    public void ReturnDocInfo() throws Exception {
        String sql = "update DocDetail set docstatus=? where id=?";

        RecordSet statement = new RecordSet();

        try {

            statement.executeUpdate(sql,docstatus,id);
            log.resetParameter();
            log.setDocId(this.id);
            log.setDocSubject(this.docsubject);
            log.setOperateType("5");
            log.setOperateUserid(userid);
            log.setUsertype(this.usertype);
            log.setClientAddress(this.clientip);
            log.setDocCreater(this.doccreaterid);
            log.setDocLogInfo();
        } catch (Exception e) {
            writeLog(e);
            throw e;
        } finally {
        }
    }

    /**
     * 重打开一个文档
     * 
     * @throws Exception
     */
    public void ReopenDocInfo() throws Exception {
        String sql = "update DocDetail set docapproveuserid=?,docapprovedate=?,docapprovetime=?,docstatus=? where id=?";

        RecordSet statement = new RecordSet();
        try {

            statement.executeUpdate(sql,0,"","",docstatus,id);
            log.resetParameter();
            log.setDocId(this.id);
            log.setDocSubject(this.docsubject);
            log.setOperateType("6");
            log.setOperateUserid(userid);
            log.setUsertype(this.usertype);
            log.setClientAddress(this.clientip);
            log.setDocCreater(this.doccreaterid);
            log.setDocLogInfo();
        } catch (Exception e) {
            writeLog(e);
            throw e;
        } finally {
        }
    }

    /**
     * 删除一个文档
     * 
     * @throws Exception
     */
    public void DeleteDocInfo() throws Exception {
        DocExtUtil deu = new DocExtUtil();
        try {
            deu.deleteDoc(this.id);

            log.resetParameter();
            log.setDocId(this.id);
            log.setDocSubject(this.docsubject);
            //log.setOperateType("2");
            log.setOperateType("3");           
            log.setOperateUserid(userid);
            log.setUsertype(this.usertype);
            log.setClientAddress(this.clientip);
            log.setDocCreater(this.doccreaterid);
            log.setCreatertype(this.docCreaterType);
            log.setDocLogInfo();
        } catch (Exception e) {
            writeLog(e);
            throw e;
        } finally {
            try {
               // statement.close();
            } catch (Exception ex) {
            }
        }
    }

    /**
     * 得到文档的扩展名
     * 
     * @param file 文档全名
     * @return 文档的扩展名
     */
    public String getFileExt(String file) {
        if (file == null || file.trim().equals("")) {
            return "";
        } else {
            int idx = file.lastIndexOf(".");
            if (idx == -1) {
                return "";
            } else {
                if (idx + 1 >= file.length()) {
                    return "";
                } else {
                    return file.substring(idx + 1);
                }
            }
        }
    }

    /**
     * add by wjy 保存自定义数据
     * 
     * @param fu
     * @param docId
     */
    private void addCustomData(FileUpload fu, int docId) {
        int secid = Util.getIntValue(fu.getParameter("seccategory"), 0);
        CustomFieldManager cfm = new CustomFieldManager("DocCustomFieldBySecCategory", secid);
        cfm.getCustomFields();
        String sql = "insert into cus_fielddata";
        String nameStr = "";
        String valueStr = "";
        while (cfm.next()) {
            nameStr += "," + cfm.getFieldName(""+cfm.getId());
            if (cfm.getFieldDbType().startsWith("text") || cfm.getFieldDbType().startsWith("char")
                    || cfm.getFieldDbType().startsWith("varchar")|| cfm.getFieldDbType().startsWith("browser")) {
                valueStr += ",'" + Util.null2String(fu.getParameter("customfield" + cfm.getId())) + "'";
            } else {
                if (Util.null2String(fu.getParameter("customfield" + cfm.getId())).equals("")) {
                    valueStr += ",null";
                } else {
                    valueStr += "," + Util.null2String(fu.getParameter("customfield" + cfm.getId()));
                }
            }
        }
        if (!nameStr.equals("")) {
            nameStr = nameStr.substring(1);
            valueStr = valueStr.substring(1);

            sql += "(scope,scopeid,id," + nameStr + ") values('DocCustomFieldBySecCategory'," + secid + "," + docId
                    + "," + valueStr + ")";
            // System.out.println("sql = " + sql);
            RecordSet rs=new RecordSet();
            rs.executeSql(sql);
        }

    }

    /**
     * add by wjy 编辑自定义数据
     * 
     * @param fu
     * @param docId
     */
    private void editCustomData(FileUpload fu, int docId) {
        int secid = Util.getIntValue(fu.getParameter("seccategory"), 0);
        RecordSet rsSql = new RecordSet();
        rsSql.executeSql("select id from cus_fielddata where scope='DocCustomFieldBySecCategory' and scopeid=" + secid
                + " and id=" + docId);
        int rsCount=rsSql.getCounts();        
        if (rsSql.next()&&rsCount==1) {
            CustomFieldManager cfm = new CustomFieldManager("DocCustomFieldBySecCategory", secid);
            cfm.getCustomFields();
            String sql = "update cus_fielddata set ";
            String setStr = "";
            while (cfm.next()) {
                setStr += "," + cfm.getFieldName(""+cfm.getId()) + "=";
                if (cfm.getFieldDbType().startsWith("text") || cfm.getFieldDbType().startsWith("char")
                        || cfm.getFieldDbType().startsWith("varchar")|| cfm.getFieldDbType().startsWith("browser")) {
                    setStr += "'" + Util.null2String(fu.getParameter("customfield" + cfm.getId())) + "'";
                } else {
                    if (Util.null2String(fu.getParameter("customfield" + cfm.getId())).equals("")) {
                        setStr += "null";
                    } else {
                        setStr += Util.null2String(fu.getParameter("customfield" + cfm.getId()));
                    }
                }
            }
            if (!setStr.equals("")) {
                setStr = setStr.substring(1);

                sql += setStr + " where scope='DocCustomFieldBySecCategory' and scopeid=" + secid + " and id=" + docId;
                // System.out.println("sql = " + sql);
                rsSql.executeSql(sql);
            }
        } else {
        	if(rsCount<=0){
                addCustomData(fu, docId);        		
        	}else{
        	    rsSql.executeSql("delete from cus_fielddata where scope='DocCustomFieldBySecCategory' and scopeid=" + secid
                        + " and id=" + docId);
                addCustomData(fu, docId);
        	}
        }

    }

    /**
     * add by wjy 删除自定义数据
     * 
     * @param docId
     */
    private void deleteCustomData(int docId) {
        setId(docId);
        try {
            getDocInfoById();
            RecordSet rsSql = new RecordSet();
            rsSql.executeSql("delete from cus_fielddata where scope='DocCustomFieldBySecCategory' and scopeid="
                    + getSeccategory() + " and id=" + docId);
        } catch (Exception e) {
            writeLog(this.getClass().getName(), e);
        }
    }
    
    
    /**
     * 用来识别编辑器中文本内的图片的标记. #2007-08-24 add by yeriwei!
     * @param i as int
     * @return ' alt="docimages_$i" '
     */
    public static String getImgAltFlag(int i){
    	return " alt=\"docimages_" + i + "\" ";
    }
    
    /**
     * 新建文档
     * @param fu FileUpload对象
     * @param opera 操作类型
     * @throws Exception
     */
    public void addDoc(FileUpload fu,String opera) throws Exception {
        RecordSet rs = new RecordSet();
        
        this.id = Util.getIntValue(fu.getParameter("docId"), 0);

        if (this.id == 0) {
            // 获得下一个可用的文档id
            this.id = getNextDocId(rs);
            this.docType = 1;
            this.docextendname = "html";
        } else {
            docType = 2;

            // Get Doc Extend Name
            //isextfile <> '1'是正文 TD8782
            String strSql = "select imagefilename from docimagefile where (isextfile <> '1' or isextfile is null) and docid=" + this.id;
            RecordSet rsForExtendName = new RecordSet();
            rsForExtendName.executeSql(strSql);
            if (rsForExtendName.next()) {
                String imageFileName = Util.null2String(rsForExtendName.getString(1));
                int tempPos = imageFileName.lastIndexOf(".");
                if (tempPos != -1) {
                    this.docextendname = imageFileName.substring(tempPos + 1);
                }
            }
        }

        // add by wjy for add custom data
        addCustomData(fu, this.id);

        // 开始进行存储附件的操作
        int accessorynum = Util.getIntValue(fu.getParameter("accessorynum"), 0);
        String[] needuploads = new String[accessorynum];

        for (int i = 0; i < accessorynum; i++) {
            needuploads[i] = "accessory" + (i + 1);
        }

        // 上传附件并返回存储到数据库中后附件的对应id
        String[] fileids = fu.uploadFiles(needuploads);
        // 返回附件的对应文件名称
        String[] filenames = fu.getFileNames();

        int accessorynumtrue = 0;
        
        
        /*附加新的附件,通过swfupload方法传上来的附件*/
        String imageidsExt=Util.null2String(fu.getParameter("imageidsExt"));
        String imagenamesExt=Util.null2String(fu.getParameter("imagenamesExt"));        
        ArrayList fildIdList_ext=Util.TokenizerString(imageidsExt,",");
        ArrayList fildNameList_ext=Util.TokenizerString(imagenamesExt,"|");
        
        ArrayList fileidList=new ArrayList();
        ArrayList filenameList=new ArrayList();
        
        for(int i=0;i<fileids.length;i++){
        	fileidList.add(fileids[i]);
        	filenameList.add(filenames[i]);
        }
        for(int i=0;i<fildIdList_ext.size();i++){
        	fileidList.add(fildIdList_ext.get(i));
        	filenameList.add(fildNameList_ext.get(i));
        }
        
        // 存储文档附件的相关信息和附件的id
        for (int i = 0; i < fileidList.size(); i++) {
            if (Util.getIntValue((String)fileidList.get(i), 0) == 0)       continue;
            accessorynumtrue++;
            imgManger.resetParameter();
            imgManger.setDocid(this.id);
            imgManger.setImagefileid(Util.getIntValue((String)fileidList.get(i), 0));
            imgManger.setImagefilename((String)filenameList.get(i));
            imgManger.setIsextfile("1");
            String ext = getFileExt((String)filenameList.get(i));
            if (ext.equalsIgnoreCase("doc")) {
                imgManger.setDocfiletype("3");
            } else if (ext.equalsIgnoreCase("xls")) {
                imgManger.setDocfiletype("4");
            } else if (ext.equalsIgnoreCase("ppt")) {
                imgManger.setDocfiletype("5");
            } else if (ext.equalsIgnoreCase("wps")) {
                imgManger.setDocfiletype("6");
            } else if (ext.equalsIgnoreCase("docx")) {
                imgManger.setDocfiletype("7");
            } else if (ext.equalsIgnoreCase("xlsx")) {
                imgManger.setDocfiletype("8");
            } else if (ext.equalsIgnoreCase("pptx")) {
                imgManger.setDocfiletype("9");
            } else if (ext.equalsIgnoreCase("et")) {
                imgManger.setDocfiletype("10");
            } else {
                imgManger.setDocfiletype("2");
            }
            imgManger.AddDocImageInfo();
            
            //将附件从上传临时表中删除
            rs.executeSql("delete from imagefiletemp where imagefileid = " + Util.getIntValue((String)fileidList.get(i), 0) + " and docid = 0");
        }
        
        //删除新建文档时删除的附件
        String delImageidsExt=Util.null2String(fu.getParameter("delImageidsExt"));        
        ArrayList delImageids=Util.TokenizerString(delImageidsExt,",");
        for (int i = 0; i < delImageids.size(); i++) {
        	if (Util.getIntValue((String)delImageids.get(i), 0) == 0) continue;
        	imgManger.resetParameter();
        	imgManger.setImagefileid(Util.getIntValue((String)delImageids.get(i), 0));
        	imgManger.DeleteImageInfo();
            //将附件从上传临时表中删除
            rs.executeSql("delete from imagefiletemp where imagefileid = " + Util.getIntValue((String)delImageids.get(i), 0) + " and docid = 0");
        }
        
        
        // 开始存储文档中的图片的操作 和文档附件的存储基本一样
        int docimages_num = Util.getIntValue(fu.getParameter("docimages_num"), 0);
        
        needuploads = new String[docimages_num];

        for (int i = 0; i < docimages_num; i++) {
            needuploads[i] = "docimages_" + i;
        }

        fu.needImagewidth(true);
        fileids = fu.uploadFiles(needuploads);
        filenames = fu.getFileNames();
        int[] imagesizes = fu.getFileSizes();
        int[] imagewidths = fu.getWidths();
        int[] imageheights = fu.getHeights();

        for (int i = 0; i < docimages_num; i++) {
            if (Util.getIntValue(fileids[i], 0) == 0)
                continue;
            imgManger.resetParameter();
            imgManger.setDocid(this.id);
            imgManger.setImagefileid(Util.getIntValue(fileids[i], 0));
            imgManger.setImagefilename(filenames[i]);
            imgManger.setDocfiletype("1");

            imgManger.setImagefielsize(imagesizes[i]);
            imgManger.setimagefilewidth(imagewidths[i]);
            imgManger.setImagefileheight(imageheights[i]);
            
            imgManger.AddDocImageInfo();
        }

        // 存储文档的内容
        this.doccontent = Util.fromBaseEncoding(fu.getParameter("doccontent"), languageid);
        this.doccontent =Util.htmlFilter4UTF8(this.doccontent );
        //替换文档内容中可能存在的 textarea|input|form 标签
        String rex_html = "<(textarea|input|form)[^>]*>";
        String rex_html2 = "</(textarea|form)>";
        
		Pattern p_script = Pattern.compile(rex_html, Pattern.CASE_INSENSITIVE);
		Matcher m_html = p_script.matcher(this.doccontent);
		this.doccontent = m_html.replaceAll("");
		
		p_script = Pattern.compile(rex_html2, Pattern.CASE_INSENSITIVE);
		m_html = p_script.matcher(this.doccontent);
		this.doccontent = m_html.replaceAll("");
        
        this.updateDocImageFileOfPic(this.id,this.doccontent);

        String moduleimages[] = fu.getParameters("moduleimages");

        // 如果文档中图片的路径是全路径则将其改为相对路径使其不含服务器的路径。
        if (moduleimages != null && moduleimages.length > 0) {
            int tmppos = doccontent.indexOf("/weaver/weaver.file.FileDownload?fileid=");
            while (tmppos != -1) {
                int startpos = doccontent.lastIndexOf("\"", tmppos);
                if ((tmppos - startpos) > 1) {
                    String tmpcontent = doccontent.substring(0, startpos + 1);
                    tmpcontent += doccontent.substring(tmppos);
                    doccontent = tmpcontent;
                    tmppos = doccontent.indexOf("/weaver/weaver.file.FileDownload?fileid=", tmppos + 1);
                } else
                    tmppos = doccontent.indexOf("/weaver/weaver.file.FileDownload?fileid=", tmppos + 1);
            }
        }

        for (int i = 0; i < docimages_num; i++) {
            int pos = doccontent.indexOf(getImgAltFlag(i));
            // 如果此文档有相关的图片 则把其组合成正确的下载路径
            if (pos != -1) {
                int temppos = pos;
                String tmpcontent = doccontent.substring(0, pos);
                tmpcontent += " alt=\"" + filenames[i] + "\" ";

                pos = doccontent.indexOf("src=\"", pos);
                int endpos = doccontent.indexOf("\"", pos + 5);

                tmpcontent += doccontent.substring(temppos + getImgAltFlag(i).length(), pos);
                tmpcontent += "src=\""+weaver.general.GCONST.getContextPath()+"/weaver/weaver.file.FileDownload?fileid=" + Util.getFileidOut(fileids[i]);
                tmpcontent += "\"";
                tmpcontent += doccontent.substring(endpos + 1);
                doccontent = tmpcontent;
            }
            // 如果没有这个相关的图片文件，则删除和此文档相关地这个图片的数据
            else {
                imgManger.resetParameter();
                imgManger.setImagefileid(fileids[i]);
                imgManger.setDocid(this.id);
                imgManger.DeleteSingleDocImageInfo();
            }
        }

        // ...
        if (moduleimages != null) {
            for (int i = 0; i < moduleimages.length; i++) {
                String moduleimageid = moduleimages[i];
                rs.executeProc("imagefile_AddByDoc", moduleimageid);
            }
        }

        // 下面的操作可以得到此知识文档的相关资料
        Calendar today = Calendar.getInstance();
        String formatdate = Util.add0(today.get(Calendar.YEAR), 4) + "-"
                + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-"
                + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);
        String formattime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":"
                + Util.add0(today.get(Calendar.MINUTE), 2) + ":" + Util.add0(today.get(Calendar.SECOND), 2);

        this.maincategory = Util.getIntValue(fu.getParameter("maincategory"), 0);
        this.subcategory = Util.getIntValue(fu.getParameter("subcategory"), 0);
        this.seccategory = Util.getIntValue(fu.getParameter("seccategory"), 0);
        this.doclangurage = Util.getIntValue(fu.getParameter("doclangurage"), 0);
        //this.docapprovable = fu.getParameter("docapprovable");
        this.docreplyable = fu.getParameter("docreplyable");
        this.isreply = Util.null2String(fu.getParameter("isreply"));
        this.replydocid = Util.getIntValue(fu.getParameter("replydocid"), 0);
        this.ownerid = Util.getIntValue(fu.getParameter("ownerid"), 0);
        this.ownerType = this.usertype;       
        this.docsubject = Util.toHtml2(fu.getParameter("docsubject"));
        this.docsubject = interceptString(this.docsubject,400);
        
        this.docpublishtype = fu.getParameter("docpublishtype");
        if (docpublishtype.equals("2")) {
            //String docmain = fu.getParameter("docmain");
        	String docmain = Util.toHtml2(Util.encodeAnd(Util.null2String(fu.getParameter("docmain"))));            
            this.doccontent = docmain + "!@#$%^&*" + this.doccontent;
        }

        this.itemid = Util.getIntValue(fu.getParameter("itemid"), 0);
        this.itemmaincategoryid = Util.getIntValue(fu.getParameter("itemmaincategoryid"), 0);
        this.hrmresid = Util.getIntValue(fu.getParameter("hrmresid"), 0);
        this.assetid = Util.getIntValue(fu.getParameter("assetid"), 0);
        this.crmid = Util.getIntValue(fu.getParameter("crmid"), 0);
        this.projectid = Util.getIntValue(fu.getParameter("projectid"), 0);
        this.financeid = Util.getIntValue(fu.getParameter("financeid"), 0);
        this.doccreaterid = this.userid;
        this.docCreaterType=this.usertype;
        // TD1715 新建或者编辑文档时，更改文档的所有者，促使文档所在的部门被清除 DP
//        this.docdepartmentid = Util.getIntValue(hrc.getDepartmentID("" + ownerid));
        // this.docdepartmentid =
        // Util.getIntValue(fu.getParameter("docdepartmentid"), 0);
        
        if("2".equals(this.ownerType)){
        	this.docdepartmentid = Util.getIntValue(hrc.getDepartmentID("" + cici.getCustomerInfomanager(""+ownerid)));
        }else{
        	this.docdepartmentid = Util.getIntValue(hrc.getDepartmentID("" + ownerid));
        }

        this.doccreatedate = formatdate;
        this.doccreatetime = formattime;
        this.doclastmoduserid = this.userid;
        this.docLastModUserType=this.usertype;
        this.doclastmoddate = formatdate;
        this.doclastmodtime = formattime;
        this.docapproveuserid = 0;
        this.docApproveUserType = "";
        this.docapprovedate = "";
        this.docapprovetime = "";
        this.docarchiveuserid = 0;
        this.docArchiveUserType = "";
        this.docarchivedate = "";
        this.docarchivetime = "";
        this.newsid = Util.getIntValue(fu.getParameter("newsid"), 0);

        rs = new RecordSet();
        SysRemindWorkflow srw = new SysRemindWorkflow();
        String sql = "";
        if (replydocid != 0) {
            sql = "select id,canremind,docsubject,doccreaterid from DocDetail where id=" + replydocid;
            //System.out.println("sql = " + sql);
            String canRemind = "";
            rs.executeSql(sql);
            if (rs.next()) {
                canRemind = rs.getString("canremind");
                if (canRemind.equals("2")) {
                    srw.setSysRemindInfo("回复提醒:" + rs.getString("docsubject"), this.id, 0, 0, 0, this.userid,
                            rs.getString("doccreaterid") + "", "");
                }
            }
        }

        if (Util.null2String(fu.getParameter("parentids")).equals("")) {
            this.parentids = this.id + "";
        } else {
            this.parentids = Util.null2String(fu.getParameter("parentids")) + "," + this.id;
        }

        this.keyword = Util.null2String(fu.getParameter("keyword"));
        /* 文档的关键字 */

        int docid = this.id;

        this.accessorycount = accessorynumtrue;

        if (isreply.equals("1")) {
            AddReplayDocCount(rs); // 修改回复记录条数
        }

        /* 回复文档总数 */
        this.replaydoccount = 0;
        /* 创建的用户类型 1: 内部 2: 外部 */
        //this.usertype = Util.null2String(fu.getParameter("usertype"));
        this.topage = Util.null2String(fu.getParameter("topage"));

        this.contractman = Util.null2String(fu.getParameter("contractman"));
        this.contractstartdate = Util.null2String(fu.getParameter("contractstartdate"));
        this.contractenddate = Util.null2String(fu.getParameter("contractenddate"));
        this.docmodule = Util.null2String(fu.getParameter("docmodule"));
        this.proenddate = Util.null2String(fu.getParameter("proenddate"));
        this.typeid = Util.getIntValue(fu.getParameter("typeid"), 0);
        this.urlfrom = Util.null2String(fu.getParameter("urlfrom"));
        this.canCopy = "" + Util.getIntValue(fu.getParameter("cancopy"), 1);
        this.canRemind = "" + Util.getIntValue(fu.getParameter("canremind"), 1);

        // get catagory's orderable
        this.orderable = "" + scc.getSecOrderable(this.seccategory);
        
        this.docEdition = Util.getIntValue(fu.getParameter("docedition"),-1);
        this.docEditionId = Util.getIntValue(fu.getParameter("doceditionid"),-1);
        
        this.mainDoc = Util.getIntValue(Util.null2String(fu.getParameter("maindoc")),-1);
        if(this.mainDoc==-1) this.mainDoc = this.id;
        
        // added by wdl
        this.docCode = Util.null2String(fu.getParameter("doccode"));
        if(this.docCode.equals("")){
            DocCoder dc = new DocCoder();
            if(this.mainDoc == this.id){
            	this.docCode = dc.getDocCoder(""+this.seccategory);
            }else{
            	this.docCode = dc.getSecDocCoder(""+mainDoc,""+this.seccategory);
            }
        }
        
        this.readOpterCanPrint = Util.getIntValue(fu.getParameter("readoptercanprint"), 0);
        
        this.invalidationDate = Util.null2String(fu.getParameter("invalidationdate"));
		this.dummycata = Util.null2String(fu.getParameter("dummycata"));
        
        if(scc.isNoRepeatedName(this.seccategory)){
            // TODO
            
        }
        
        this.docstatus = fu.getParameter("docstatus");
        
        // 如果在目录上设置了 创建者对此目录下的文档无权限查看则此文档被直接置为正常 TD4111 TD4112 begin
        RecordSet rsCreater = new RecordSet();
        int pcreater = 3;
        String strCreaterSql = "select pcreater from secCreaterDocPope where secid=" + this.seccategory;

        rsCreater.executeSql(strCreaterSql);
        if (rsCreater.next()) {
            pcreater = Util.getIntValue(rsCreater.getString("pcreater"), 0);
        }
        
        /*
        if (pcreater <= 0) { // 创建者对文档无权限
            if("1".equals(this.docapprovable))
                docstatus = "3"; // 需要审批则置成审批状态
            else
                docstatus = "1"; // 不需要审批直接置成正常状态
        }
        */
        // end
        // 判断新建的是不是个人文档
        String from = Util.null2String(fu.getParameter("from"));

        //保存草稿//预览
        if(opera.equals("adddraft") || opera.equals("addpreview")){
            this.docstatus = "0";
        } else if(!"personalDoc".equals(from)){//提交
            if(scc.needApprove(this.seccategory)) {//如果需要审批
                this.docstatus = "-3";
                this.approveType = 1;
            } else if(scc.needPubOperation(this.seccategory)) {//如果需要发布
                this.docstatus = "-6";
            } else {//生效/正常
                this.docstatus = "-1";
                this.docValidUserId = this.userid;
                this.docValidUserType=this.usertype;
                this.docValidDate = formatdate;
                this.docValidTime = formattime;
                
                if(scc.isEditionOpen(this.seccategory)) {//如果版本管理开启
                    if(this.docEditionId == -1){// 如果不存在历史版本
                        this.docEditionId = this.getNextEditionId(rs);
                    } else {
                        // TODO 否则，通过版本ID找到同文档的版本
                        //新建文档不存在以前有版本
                    }
                    this.docEdition = dc.getEdition(this.docEditionId)+1;
                }
            }
            
            if(this.invalidationDate!=null&&!"".equals(this.invalidationDate)){
                java.text.DateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
                Date tmpidate = sdf.parse(this.invalidationDate);
            	if(tmpidate.getTime()<today.getTime().getTime()){
            		this.docstatus = "7";
                    this.docInvalUserId = this.userid;
                    this.docInvalUserType = this.usertype;
                    this.docInvalDate = formatdate;
                    this.docInvalTime = formattime;
                    
                    if(scc.isEditionOpen(this.seccategory)) {//如果版本管理开启
                    	if(scc.needApprove(this.seccategory)||scc.needPubOperation(this.seccategory)) {//如果需要审批或者需要发布
                            if(this.docEditionId==-1)
                                this.docEditionId = this.getNextEditionId(rs);
                            this.docEdition = dc.getEdition(this.docEditionId)+1;                    		
                    	}
                    }                      
            	}
            }
        }
        if (!contractman.equals("")) {
            this.docstatus = "1";
            docCreaterType="1";
        }
        this.canPrintedNum = Util.getIntValue(fu.getParameter("canPrintedNum"),0);
        this.editMouldId = Util.getIntValue(fu.getParameter("editMouldId"),0);
        
        this.secretLevel = Util.getIntValue(fu.getParameter("secretLevel"),DEFAILT_SECRET_LEVEL);
        this.secretValidity = Util.null2s(fu.getParameter("secretValidity"),"");

        this.replyremind = Util.getIntValue(fu.getParameter("replyremind"),0);

        // 进行实际的保存文档内容的操作
        AddDocInfo();


        if (!contractman.equals("")) {
            addHrmContract();
        }else{
            // 进行保存共享信息的实际操作
            AddShareInfo();
        }
    }
    
    
    
    
    public void setDocType(int docType) {
		this.docType = docType;
	}

	/**
     * 编辑文档
     * @param fu FileUpload对象
     * @param opera 操作类型
     * @throws Exception
     */
    public void editDoc(FileUpload fu,String opera) throws Exception {
        // 编辑的时候进行的操作 基本通新增的时候的操作
        RecordSet rs = new RecordSet();
        
        this.id = Util.getIntValue(fu.getParameter("id"), 0);
        this.oldVersionId = Util.getIntValue(fu.getParameter("versionId"), 0);
        String versionDetail = Util.null2String(fu.getParameter("versionDetail"));
        //add by wdl
        int oldDocId = -1;
        boolean needAddNewEdition = false;
        this.imageFileIdOfPicChangeList=new ArrayList();
       
        this.maincategory = Util.getIntValue(fu.getParameter("maincategory"), 0);
        this.subcategory = Util.getIntValue(fu.getParameter("subcategory"), 0);
        this.seccategory = Util.getIntValue(fu.getParameter("seccategory"), 0);
        
        this.docstatus = fu.getParameter("docstatus");
        this.oldstatus = docstatus;
        this.docCode = Util.null2String(fu.getParameter("doccode"));
        this.docEdition = Util.getIntValue(fu.getParameter("docedition"),-1);
        this.docEditionId = Util.getIntValue(fu.getParameter("doceditionid"),-1);
        this.docsubject = Util.toHtml2(Util.null2String(fu.getParameter("docsubject")));
        this.docsubject = interceptString(this.docsubject,400);
		
        String deleteaccessory = Util.null2String(fu.getParameter("deleteaccessory"));
        if(deleteaccessory.startsWith(",")) deleteaccessory = deleteaccessory.substring(1);
        if(deleteaccessory.endsWith(",")) deleteaccessory = deleteaccessory.substring(0,deleteaccessory.length()-1);
        
        //需要拷贝当前版本的文档新建为草稿文档后再作操作
        //if(scc.isEditionOpen(this.seccategory)&&this.docEdition>0&&!"0".equals(this.oldstatus)) {
        //if(scc.isEditionOpen(this.seccategory)&&!"0".equals(this.oldstatus)&&!"4".equals(this.oldstatus)) {       	
        if(scc.isEditionOpen(this.seccategory)&&((!"0".equals(this.oldstatus)&&!"4".equals(this.oldstatus))||(this.docEditionId>0&&this.docEdition>0))) {       	

            needAddNewEdition = true;
            oldDocId = this.id;
            // 获得一个新版本的文档id
            this.id = getNextDocId(rs);        	
        	
        	if(this.docEditionId<=0) {//之前一个版本为非版本管理
                this.docEditionId = this.getNextEditionId(rs);
                this.docEdition = 1;                 
                rs.executeSql("update DocDetail set docEditionId="+this.docEditionId+",docEdition="+this.docEdition+" where id="+oldDocId);
                rs.executeSql("update docdetail set docstatus = 7,ishistory = 1 where id <> " + this.id + " and docedition > 0 and docedition <= " + this.docEdition + " and doceditionid > 0 and doceditionid = " + this.docEditionId);    
            }else if(this.docEdition<=0){//之前一个版本没有设置版本号  如为审批状态
                this.docEdition = dc.getEdition(this.docEditionId)+1;            	
                rs.executeSql("update DocDetail set docEditionId="+this.docEditionId+",docEdition="+this.docEdition+" where id="+oldDocId);
                rs.executeSql("update docdetail set docstatus = 7,ishistory = 1 where id <> " + this.id + " and docedition > 0 and docedition <= " + this.docEdition + " and doceditionid > 0 and doceditionid = " + this.docEditionId);                
            }else if(this.docEditionId>0&&this.docEdition>0){
                rs.executeSql("update docdetail set docstatus = 7,ishistory = 1 where id <> " + this.id + " and docedition > 0 and docedition <= " + this.docEdition + " and doceditionid > 0 and docstatus in (0,4,-6,-3,-1) and doceditionid = " + this.docEditionId);             	
            }

            //拷贝原文档到新文档
            addNewDocForEdition(oldDocId,deleteaccessory);
            
            RecordSet rs1 = new RecordSet();
            List isExistedImageFileIds = new ArrayList();
            rs1.executeSql("select * from DocImageFile where docid ="+oldDocId);
            while(rs1.next()){
            	isExistedImageFileIds.add(Util.null2String(rs1.getString("imagefileid")));
            }
            
            /*附加新的附件,通过swfupload方法传上来的附件*/
            String imageidsExt=Util.null2String(fu.getParameter("imageidsExt"));
            String imagenamesExt=Util.null2String(fu.getParameter("imagenamesExt"));        
            ArrayList fildIdList_ext=Util.TokenizerString(imageidsExt,",");
            ArrayList fildNameList_ext=Util.TokenizerString(imagenamesExt,"|");
            ArrayList fileidList=new ArrayList();
            ArrayList filenameList=new ArrayList();
            for(int i=0;i<fildIdList_ext.size();i++){
            	fileidList.add(fildIdList_ext.get(i));
            	filenameList.add(fildNameList_ext.get(i));
            }
            // 存储文档附件的相关信息和附件的id
            for (int i = 0; i < fileidList.size(); i++) {
                if(Util.getIntValue((String)fileidList.get(i), 0) == 0) continue;
                if(isExistedImageFileIds.indexOf(Util.null2String((String)fileidList.get(i)))>-1) continue; 
                imgManger.resetParameter();
                imgManger.setDocid(this.id);
                imgManger.setImagefileid(Util.getIntValue((String)fileidList.get(i), 0));
                imgManger.setImagefilename((String)filenameList.get(i));
                imgManger.setIsextfile("1");
                String ext = getFileExt((String)filenameList.get(i));
                if (ext.equalsIgnoreCase("doc")) {
                    imgManger.setDocfiletype("3");
                } else if (ext.equalsIgnoreCase("xls")) {
                    imgManger.setDocfiletype("4");
                } else if (ext.equalsIgnoreCase("ppt")) {
                    imgManger.setDocfiletype("5");
                } else if (ext.equalsIgnoreCase("wps")) {
                    imgManger.setDocfiletype("6");
                } else if (ext.equalsIgnoreCase("docx")) {
                    imgManger.setDocfiletype("7");
                } else if (ext.equalsIgnoreCase("xlsx")) {
                    imgManger.setDocfiletype("8");
                } else if (ext.equalsIgnoreCase("pptx")) {
                    imgManger.setDocfiletype("9");
                } else if (ext.equalsIgnoreCase("et")) {
                    imgManger.setDocfiletype("10");
                } else {
                    imgManger.setDocfiletype("2");
                }
                imgManger.AddDocImageInfo();
                
                //将附件从上传临时表中删除
                rs.executeSql("delete from imagefiletemp where imagefileid = " + Util.getIntValue((String)fileidList.get(i), 0) + " and docid = "+oldDocId);
            	rs.executeSql(" update docdetail set accessorycount = (select count(distinct id) from DocImageFile where isextfile = '1' and docid = " + this.id + " and docfiletype <> '1'  and docfiletype <> '11' ) where id = " + this.id);
            }

            this.docEdition = -1;
        } else if(Util.getIntValue(Util.null2String(fu.getParameter("isFromAccessory")))==1 || (scc.isEditionOpen(this.seccategory)&&("0".equals(this.oldstatus)||"4".equals(this.oldstatus)))){
			RecordSet rs1 = new RecordSet();
             List isExistedImageFileIds = new ArrayList();
             rs1.executeSql("select * from DocImageFile where docid ="+this.id);
             while(rs1.next()){
             	isExistedImageFileIds.add(Util.null2String(rs1.getString("imagefileid")));
             }
             /*附加新的附件,通过swfupload方法传上来的附件*/
             String isSubmit = Util.null2String(fu.getParameter("isSubmit"));
             String imageidsExt=Util.null2String(fu.getParameter("imageidsExt"));
             String imagenamesExt=Util.null2String(fu.getParameter("imagenamesExt"));        
             ArrayList fildIdList_ext=Util.TokenizerString(imageidsExt,",");
             ArrayList fildNameList_ext=Util.TokenizerString(imagenamesExt,"|");
             ArrayList fileidList=new ArrayList();
             ArrayList filenameList=new ArrayList();
             for(int i=0;i<fildIdList_ext.size();i++){
             	fileidList.add(fildIdList_ext.get(i));
             	filenameList.add(fildNameList_ext.get(i));
             }
            	 // 存储文档附件的相关信息和附件的id
               for (int i = 0; i < fileidList.size(); i++) {
                   if(Util.getIntValue((String)fileidList.get(i), 0) == 0) continue;
                   if(isExistedImageFileIds.indexOf(Util.null2String((String)fileidList.get(i)))>-1) continue; 
                   imgManger.resetParameter();
                   imgManger.setDocid(this.id);
                   imgManger.setImagefileid(Util.getIntValue((String)fileidList.get(i), 0));
                   imgManger.setImagefilename((String)filenameList.get(i));
                   imgManger.setIsextfile("1");
                   String ext = getFileExt((String)filenameList.get(i));
                   if (ext.equalsIgnoreCase("doc")) {
                       imgManger.setDocfiletype("3");
                   } else if (ext.equalsIgnoreCase("xls")) {
                       imgManger.setDocfiletype("4");
                   } else if (ext.equalsIgnoreCase("ppt")) {
                       imgManger.setDocfiletype("5");
                   } else if (ext.equalsIgnoreCase("wps")) {
                       imgManger.setDocfiletype("6");
                   } else if (ext.equalsIgnoreCase("docx")) {
                       imgManger.setDocfiletype("7");
                   } else if (ext.equalsIgnoreCase("xlsx")) {
                       imgManger.setDocfiletype("8");
                   } else if (ext.equalsIgnoreCase("pptx")) {
                       imgManger.setDocfiletype("9");
                   } else if (ext.equalsIgnoreCase("et")) {
                       imgManger.setDocfiletype("10");
                   } else {
                       imgManger.setDocfiletype("2");
                   }
                   imgManger.AddDocImageInfo();
				    //将附件从上传临时表中删除
                   rs.executeSql("delete from imagefiletemp where imagefileid = " + Util.getIntValue((String)fileidList.get(i), 0) + " and docid = "+this.id);
                   rs.executeSql(" update docdetail set accessorycount = (select count(distinct id) from DocImageFile where isextfile = '1' and docid = " + this.id + " and docfiletype <> '1'  and docfiletype <> '11') where id = " + this.id);
                }
               String[] deleteaccessoryArray = deleteaccessory.split(",");
               for(int j = 0;j<deleteaccessoryArray.length;j++){
            	   if(deleteaccessoryArray[j] != null && !deleteaccessoryArray[j].equals("")){
            		   String sql = "delete from docimagefile where docid = " + this.id + " and imagefileid = "+ deleteaccessoryArray[j]+"";
            		   rs.executeSql(sql);
            	   }
               }
        	rs.executeSql(" delete from docimagefile where docid = " + this.id + " and imagefileid in (select imagefiledesc from docimagefile where isextfile = '1' and docid = -" + this.id + ")");
        	rs.executeSql(" update imagefile set imagefileused = imagefileused - 1 where imagefileid in (select imagefiledesc from docimagefile where isextfile = '1' and docid = -" + this.id + ")");
        	rs.executeSql(" update docimagefile set imagefiledesc = '' where isextfile = '1' and docid = -" + this.id);
        	rs.executeSql(" update docimagefile set docid = " + this.id + " where docid = -" + this.id);
        	rs.executeSql(" update docdetail set accessorycount = (select count(distinct id) from DocImageFile where isextfile = '1' and docid = " + this.id + " and docfiletype <> '1'  and docfiletype <> '11') where id = " + this.id);
        }else if(!scc.isEditionOpen(this.seccategory)) { //版本管理尚未启用，复制生成的正文被编辑时

        	int tempImageFileId=0;
            rs.executeSql("select imagefileid from docimagefile where versionId = " + this.oldVersionId + " and docid = " + this.id);
            if(rs.next()){
            	tempImageFileId = Util.getIntValue(Util.null2String(rs.getString("imagefileid")));
            }

            boolean otherrelated = false;
            rs.executeSql("select imagefileused from imagefile where imagefileid = " + tempImageFileId);
            if(rs.next()&&Util.getIntValue(Util.null2String(rs.getString(1)))>1) {
            	otherrelated = true;        	
            }
            if(otherrelated){
            	rs.executeSql(" delete from docimagefile where docid = " + this.id + " and imagefileid in (select imagefiledesc from docimagefile where isextfile = '1' and docid = -" + this.id + ")");
            	rs.executeSql(" update imagefile set imagefileused = imagefileused - 1 where imagefileid in (select imagefiledesc from docimagefile where isextfile = '1' and docid = -" + this.id + ")");
            	rs.executeSql(" update docimagefile set imagefiledesc = '' where isextfile = '1' and docid = -" + this.id);
            	rs.executeSql(" update docimagefile set docid = " + this.id + " where docid = -" + this.id);
            	rs.executeSql(" update docdetail set accessorycount = (select count(distinct id) from DocImageFile where isextfile = '1' and docid = " + this.id + " and docfiletype <> '1'   and docfiletype <> '11') where id = " + this.id);            	
            }
        }

        // add by wjy for edit custom data
        editCustomData(fu, this.id);

        this.doccontent = Util.fromBaseEncoding(fu.getParameter("doccontent"), languageid);
        this.doccontent =Util.htmlFilter4UTF8(this.doccontent );
		int doccontentflag = Util.getIntValue(fu.getParameter("doccontentflag"),-1);
        if(doccontentflag==1){//草稿状态提交的时候  不改变文档内容
        	DocManager dm2=new DocManager();
        	dm2.resetParameter();
        	dm2.setId(this.id);
        	dm2.getDocInfoById();
        	this.doccontent=dm2.getDoccontent();
        }
        //替换文档内容中可能存在的 textarea|input|form 标签
        String rex_html = "<(textarea|input|form)[^>]*>";
        String rex_html2 = "</(textarea|form)>";
        
		Pattern p_script = Pattern.compile(rex_html, Pattern.CASE_INSENSITIVE);
		Matcher m_html = p_script.matcher(this.doccontent);
		this.doccontent = m_html.replaceAll("");
		
		p_script = Pattern.compile(rex_html2, Pattern.CASE_INSENSITIVE);
		m_html = p_script.matcher(this.doccontent);
		this.doccontent = m_html.replaceAll("");
		
        if(this.imageFileIdOfPicChangeList!=null&&this.imageFileIdOfPicChangeList.size()>0){
        	Map imageFileIdOfPicChangeMap=null;
        	int oldImageFileId=0;
        	int newImageFileId=0;
        	for(int i=0;i<this.imageFileIdOfPicChangeList.size();i++){
        		imageFileIdOfPicChangeMap=(Map)imageFileIdOfPicChangeList.get(i);
        		oldImageFileId=Util.getIntValue((String)imageFileIdOfPicChangeMap.get("oldImageFileId"));
        		newImageFileId=Util.getIntValue((String)imageFileIdOfPicChangeMap.get("newImageFileId"));
        		if(oldImageFileId!=newImageFileId){
        			this.doccontent=Util.StringReplace(this.doccontent, "/weaver/weaver.file.FileDownload?fileid="+oldImageFileId+"\"", "/weaver/weaver.file.FileDownload?fileid="+newImageFileId+"\"");
        			this.doccontent=Util.StringReplace(this.doccontent, "/weaver/weaver.file.FileDownload?fileid="+oldImageFileId+"&", "/weaver/weaver.file.FileDownload?fileid="+newImageFileId+"&");       			
        		}
        	}
        }
        this.updateDocImageFileOfPic(this.id,this.doccontent);        
        
        int tmppos = doccontent.indexOf("/weaver/weaver.file.FileDownload?fileid=");
        while (tmppos != -1) {
            int startpos = doccontent.lastIndexOf("\"", tmppos);
            if ((tmppos - startpos) > 1) {
                String tmpcontent = doccontent.substring(0, startpos + 1);
                tmpcontent += doccontent.substring(tmppos);
                doccontent = tmpcontent;
                tmppos = doccontent.indexOf("/weaver/weaver.file.FileDownload?fileid=", tmppos + 1);
            } else
                tmppos = doccontent.indexOf("/weaver/weaver.file.FileDownload?fileid=", tmppos + 1);
        }

        int olddocimagesnum = Util.getIntValue(fu.getParameter("olddocimagesnum"), 0);
		if(needAddNewEdition){
        	olddocimagesnum=0;
        }
        // 删除老的文档图片数据
        for (int i = 0; i < olddocimagesnum; i++) {
            String tmpid = Util.null2String(fu.getParameter("olddocimages" + i));
            String tmpid1 = "/weaver/weaver.file.FileDownload?fileid=" + tmpid + "\"";
            if (doccontent.indexOf(tmpid1) == -1) {
                imgManger.resetParameter();
                imgManger.setImagefileid(tmpid);
                imgManger.setDocid(this.id);
                imgManger.DeleteSingleDocImageInfo();
            }
        }

        // 增加新的文档附件数据
        int accessorynum = Util.getIntValue(fu.getParameter("accessorynum"), 0);
        String[] needuploads = new String[accessorynum];
        for (int i = 0; i < accessorynum; i++) {
            needuploads[i] = "accessory" + (i + 1);
        }

        String[] fileids = fu.uploadFiles(needuploads);
        String[] filenames = fu.getFileNames();

        int accessorynumtrue = 0;
        for (int i = 0; i < accessorynum; i++) {
            if (Util.getIntValue(fileids[i], 0) == 0)
                continue;
            accessorynumtrue++;
            imgManger.resetParameter();
            imgManger.setDocid(this.id);
            imgManger.setImagefileid(Util.getIntValue(fileids[i], 0));
            imgManger.setImagefilename(filenames[i]);
            imgManger.setIsextfile("1");
            String ext = getFileExt(filenames[i]);
            if (ext.equals("doc")) {
                imgManger.setDocfiletype("3");
            } else if (ext.equals("xls")) {
                imgManger.setDocfiletype("4");
            } else if (ext.equalsIgnoreCase("ppt")) {
                imgManger.setDocfiletype("5");
            } else if (ext.equalsIgnoreCase("wps")) {
                imgManger.setDocfiletype("6");
            } else if (ext.equalsIgnoreCase("docx")) {
                imgManger.setDocfiletype("7");
            } else if (ext.equalsIgnoreCase("xlsx")) {
                imgManger.setDocfiletype("8");
            } else if (ext.equalsIgnoreCase("pptx")) {
                imgManger.setDocfiletype("9");
            } else if (ext.equalsIgnoreCase("et")) {
                imgManger.setDocfiletype("10");
            } else {
                imgManger.setDocfiletype("2");
            }
            imgManger.AddDocImageInfo();
        }

        // 增加新的文档图片信息
        int docimages_num = Util.getIntValue(fu.getParameter("docimages_num"), 0);
        needuploads = new String[docimages_num];

        for (int i = 0; i < docimages_num; i++) {
            needuploads[i] = "docimages_" + i;
        }

        fu.needImagewidth(true);
        fileids = fu.uploadFiles(needuploads);
        filenames = fu.getFileNames();
        int[] imagesizes = fu.getFileSizes();
        int[] imagewidths = fu.getWidths();
        int[] imageheights = fu.getHeights();

        for (int i = 0; i < docimages_num; i++) {
            if (Util.getIntValue(fileids[i], 0) == 0)
                continue;
            imgManger.resetParameter();
            imgManger.setDocid(this.id);
            imgManger.setImagefileid(Util.getIntValue(fileids[i], 0));
            imgManger.setImagefilename(filenames[i]);
            imgManger.setDocfiletype("1");

            imgManger.setImagefielsize(imagesizes[i]);
            imgManger.setimagefilewidth(imagewidths[i]);
            imgManger.setImagefileheight(imageheights[i]);
            
            imgManger.AddDocImageInfo();
        }

        for (int i = 0; i < docimages_num; i++) {
            int pos = doccontent.indexOf(getImgAltFlag(i));
            if (pos != -1) {
                int temppos = pos;
                String tmpcontent = doccontent.substring(0, pos);
                tmpcontent += " alt=\"" + filenames[i] + "\" ";

                pos = doccontent.indexOf("src=\"", pos);
                int endpos = doccontent.indexOf("\"", pos + 6);

                tmpcontent += doccontent.substring(temppos + getImgAltFlag(i).length(), pos);
                tmpcontent += "src=\""+weaver.general.GCONST.getContextPath()+"/weaver/weaver.file.FileDownload?fileid=" + Util.getFileidOut(fileids[i]);
                tmpcontent += "\"";
                tmpcontent += doccontent.substring(endpos + 1);
                doccontent = tmpcontent;
            } else {
                imgManger.resetParameter();
                imgManger.setImagefileid(fileids[i]);
                imgManger.setDocid(this.id);
                imgManger.DeleteSingleDocImageInfo();
            }
        }

        Calendar today = Calendar.getInstance();
        String formatdate = Util.add0(today.get(Calendar.YEAR), 4) + "-"
                + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-"
                + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);
        String formattime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":"
                + Util.add0(today.get(Calendar.MINUTE), 2) + ":" + Util.add0(today.get(Calendar.SECOND), 2);

        this.doclangurage = Util.getIntValue(fu.getParameter("doclangurage"), 0);
        //this.docapprovable = Util.null2String(fu.getParameter("docapprovable"));
        this.docreplyable = Util.null2String(fu.getParameter("docreplyable"));
        this.isreply = Util.null2String(fu.getParameter("isreply"));
        this.replydocid = Util.getIntValue(fu.getParameter("replydocid"), 0);
        
        
        this.oldownerid = Util.getIntValue(fu.getParameter("oldownerid"), 0);

        this.docpublishtype = Util.null2String(fu.getParameter("docpublishtype"));
        this.docpublishtypeold = Util.null2String(fu.getParameter("docpublishtypeold"));

        if (docpublishtype.equals(""))
            docpublishtype = "1";
        if (docpublishtypeold.equals(""))
            docpublishtypeold = "1";

        if (docpublishtype.equals("2")&&doccontentflag!=1) {
            //String docmain = fu.getParameter("docmain");
        	String docmain = Util.toHtml2(Util.encodeAnd(Util.null2String(fu.getParameter("docmain"))));
            this.doccontent = docmain + "!@#$%^&*" + this.doccontent;
        }
        
        this.itemid = Util.getIntValue(fu.getParameter("itemid"), 0);
        this.itemmaincategoryid = Util.getIntValue(fu.getParameter("itemmaincategoryid"), 0);
        this.hrmresid = Util.getIntValue(fu.getParameter("hrmresid"), 0);
        this.assetid = Util.getIntValue(fu.getParameter("assetid"), 0);
        this.ownerid = Util.getIntValue(fu.getParameter("ownerid"), 0);
        this.ownerType = Util.null2String(fu.getParameter("ownerType"));
        this.crmid = Util.getIntValue(fu.getParameter("crmid"), 0);
        this.projectid = Util.getIntValue(fu.getParameter("projectid"), 0);
        this.financeid = Util.getIntValue(fu.getParameter("financeid"), 0);
        this.doccreaterid = Util.getIntValue(fu.getParameter("doccreaterid"), 0);
        this.docCreaterType = Util.null2String(fu.getParameter("docCreaterType"));       
        // TD1715 新建或者编辑文档时，更改文档的所有者，促使文档所在的部门被清除 DP
//        this.docdepartmentid = Util.getIntValue(hrc.getDepartmentID("" + ownerid));
        // this.docdepartmentid =
        // Util.getIntValue(fu.getParameter("docdepartmentid"), 0);

        if("2".equals(this.ownerType)){
        	this.docdepartmentid = Util.getIntValue(hrc.getDepartmentID("" + cici.getCustomerInfomanager(""+ownerid)));
        }else{
        	this.docdepartmentid = Util.getIntValue(hrc.getDepartmentID("" + ownerid));
        }        
        
        if(needAddNewEdition){
            this.doccreatedate = formatdate;
            this.doccreatetime = formattime;
        } else {
            this.doccreatedate = Util.null2String(fu.getParameter("doccreatedate"));
            this.doccreatetime = Util.null2String(fu.getParameter("doccreatetime"));
        }
        this.doclastmoduserid = this.userid;
        this.docLastModUserType = this.usertype;        
        this.doclastmoddate = formatdate;
        this.doclastmodtime = formattime;
        this.docapproveuserid = Util.getIntValue(fu.getParameter("docapproveuserid"), 0);
        this.docapprovedate = Util.null2String(fu.getParameter("docapprovedate"));
        this.docapprovetime = Util.null2String(fu.getParameter("docapprovetime"));
        this.docarchiveuserid = Util.getIntValue(fu.getParameter("docarchiveuserid"), 0);
        this.docarchivedate = Util.null2String(fu.getParameter("docarchivedate"));
        this.docarchivetime = Util.null2String(fu.getParameter("docarchivetime"));
        this.newsid = Util.getIntValue(fu.getParameter("newsid"), 0);

        this.keyword = Util.null2String(fu.getParameter("keyword")); // 文档的关键字

        this.accessorycount = accessorynumtrue;
        this.replaydoccount = Util.getIntValue(fu.getParameter("replaydoccount"), 0); // 回复文档总数
        //this.usertype = Util.null2String(fu.getParameter("usertype")); // 创建的用户类型
        // 1:
        // 内部
        // 2:
        // 外部
        this.opreateType = Util.null2String(fu.getParameter("opreateType"));
        if ("".equals(opreateType)) {
            this.opreateType = this.usertype;
        }
        this.topage = Util.null2String(fu.getParameter("topage"));
        
        this.contractman = Util.null2String(fu.getParameter("contractman"));
        this.contractstartdate = Util.null2String(fu.getParameter("contractstartdate"));
        this.contractenddate = Util.null2String(fu.getParameter("contractenddate"));
        this.docmodule = Util.null2String(fu.getParameter("docmodule"));
        this.proenddate = Util.null2String(fu.getParameter("proenddate"));
        this.typeid = Util.getIntValue(fu.getParameter("typeid"), 0);
        this.urlfrom = Util.null2String(fu.getParameter("urlfrom"));

        this.canCopy = "" + Util.getIntValue(fu.getParameter("cancopy"), 1);
        this.canRemind = "" + Util.getIntValue(fu.getParameter("canremind"), 1);
        
        // added by wdl
        this.mainDoc = Util.getIntValue(Util.null2String(fu.getParameter("maindoc")),-1);
        if(this.mainDoc==oldDocId || this.mainDoc==-1){
            this.mainDoc = this.id;
        }
        
        this.readOpterCanPrint = Util.getIntValue(fu.getParameter("readoptercanprint"), 0);
        
        this.invalidationDate = Util.null2String(fu.getParameter("invalidationdate"));
		this.dummycata = Util.null2String(fu.getParameter("dummycata"));

		this.hrmContractId = Util.getIntValue(fu.getParameter("hrmContractId"), 0);		
        
        if(scc.isNoRepeatedName(this.seccategory)){
            // TODO
            
        }
        
        //this.docstatus = fu.getParameter("docstatus");
        
        //保存草稿//预览
        if(opera.equals("editdraft") || opera.equals("editpreview")){
            this.docstatus = "0";
        } else {//提交
        	rs.executeSql("update  DocDetail set checkOutStatus='0',checkOutUserId=-1,checkOutUserType='',checkOutDate='',checkOutTime='' where id ="+this.id);         	
            if(scc.needApprove(this.seccategory)) {//如果需要审批
                if(this.oldstatus!=null&&(this.oldstatus.equals("0")||this.oldstatus.equals("4")||Util.getIntValue(this.oldstatus,0)<=0)) this.docstatus = "-3";
                else this.docstatus = "3";
                this.approveType = 1;
            } else if(scc.needPubOperation(this.seccategory)) {//如果需要发布
                if(this.oldstatus!=null&&(this.oldstatus.equals("0")||this.oldstatus.equals("4")||Util.getIntValue(this.oldstatus,0)<=0)) this.docstatus = "-6";
                else this.docstatus = "6";
            } else {//生效/正常
                if(this.oldstatus!=null&&(this.oldstatus.equals("0")||this.oldstatus.equals("4")||Util.getIntValue(this.oldstatus,0)<=0)) this.docstatus = "-1";
                else this.docstatus = "1";
                this.docValidUserId = this.userid;
                this.docValidDate = formatdate;
                this.docValidTime = formattime;
                
                if(scc.isEditionOpen(this.seccategory)) {//如果版本管理开启
                    if(this.docEditionId==-1)
                        this.docEditionId = this.getNextEditionId(rs);
                    this.docEdition = dc.getEdition(this.docEditionId)+1;
                }
            }

            if(this.invalidationDate!=null&&!"".equals(this.invalidationDate)){
                java.text.DateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
                Date tmpidate = sdf.parse(this.invalidationDate);
            	if(tmpidate.getTime()<today.getTime().getTime()){
            		this.docstatus = "7";
                    this.docInvalUserId = this.userid;
                    this.docInvalUserType = this.usertype;
                    this.docInvalDate = formatdate;
                    this.docInvalTime = formattime;
                    
                    if(scc.isEditionOpen(this.seccategory)) {//如果版本管理开启
                    	if(scc.needApprove(this.seccategory)||scc.needPubOperation(this.seccategory)) {//如果需要审批或者需要发布
                            if(this.docEditionId==-1)
                                this.docEditionId = this.getNextEditionId(rs);
                            this.docEdition = dc.getEdition(this.docEditionId)+1;                    		
                    	}
                    }                      
            	}
            }
        }
        
        this.selectedPubMouldId = Util.getIntValue(fu.getParameter("selectedpubmouldid"),-1);
        this.canPrintedNum = Util.getIntValue(fu.getParameter("canPrintedNum"),0);
        this.editMouldId = Util.getIntValue(fu.getParameter("editMouldId"),0);
        
        this.secretLevel = Util.getIntValue(fu.getParameter("secretLevel"),DEFAILT_SECRET_LEVEL);
        this.secretValidity = Util.null2s(fu.getParameter("secretValidity"),"");


        this.replyremind = Util.getIntValue(fu.getParameter("replyremind"),0);
        
        String conId = Util.null2String(fu.getParameter("conId"));
        EditDocInfo();
        editHrmContract(conId);
        
        // lyx 如果开启版本，生成新版本时，同步上一版本的回复数据
        if(scc.isEditionOpen(this.seccategory)) {//如果版本管理开启，同步回复数据
            DocReplyManager docReplyManager = new DocReplyManager();
            docReplyManager.synOldVersionReplyData(oldDocId+"", this.id+"");
        } 
        
        
        //将原有版本状态变为失效//并更新版本ID
        if((this.docstatus.equals("1")||this.docstatus.equals("-1")||this.docstatus.equals("7"))&&this.docEdition>1){
        	
        	//关联子文档
        	relateSonDocWithNewDoc(this.id);
        	
            rs.executeSql(" update docdetail set docstatus = 7,ishistory = 1 where id <> " + this.id + " and docedition > 0 and docedition < " + this.docEdition + " and doceditionid > 0 and doceditionid = " + this.docEditionId);
            
            log.resetParameter();
            log.setDocId(oldDocId);
            log.setDocSubject(this.docsubject);
            log.setOperateType("14");
            log.setOperateUserid(userid);
            log.setUsertype(this.usertype);
            log.setClientAddress(this.clientip);
            log.setDocCreater(this.doccreaterid);
            log.setDocLogInfo();
        }
	    if(this.docstatus.equals("0")){
        	relateSonDocWithNewDoc(this.id);
        }
    }
    
    private void copyDocToNewDoc(int oldDocId) throws Exception {
    	copyDocToNewDoc(oldDocId,true,"");
    }
    
    private void copyDocToNewDoc(int oldDocId,String deleteaccessory) throws Exception {
    	copyDocToNewDoc(oldDocId,true,deleteaccessory);
    }
    
    private void copyDocToNewDoc(int oldDocId,String deleteaccessory,boolean copyfile,boolean copyreallyfile) throws Exception {
    	copyDocToNewDoc(oldDocId,copyfile,deleteaccessory,false,true,"'1'",false,copyreallyfile);
    }
    
    private void copyDocToNewDoc(int oldDocId,boolean copyfile) throws Exception {
    	copyDocToNewDoc(oldDocId,copyfile,"");
    }

    private void copyDocToNewDoc(int oldDocId,boolean copyfile,String deleteaccessory) throws Exception {
    	copyDocToNewDoc(oldDocId,copyfile,deleteaccessory,false);
    }
    
    private void copyDocToNewDoc(int oldDocId,boolean copyfile,String deleteaccessory,boolean isNewDocEditionId) throws Exception {
    	//copyDocToNewDoc(oldDocId,copyfile,deleteaccessory,isNewDocEditionId,true,"'1'");
    	copyDocToNewDoc(oldDocId,copyfile,deleteaccessory,isNewDocEditionId,true,"'1'",false,false);    	
    }
    private void copyDocToNewDoc(int oldDocId,boolean copyfile,String deleteaccessory,boolean isNewDocEditionId,boolean copyRight,String newStatus,boolean isLatestOnly) throws Exception {
    	copyDocToNewDoc(oldDocId,copyfile,deleteaccessory,isNewDocEditionId,copyRight,newStatus,isLatestOnly,false);
    }
    /**
     * 复制文档到新文档
     * @param oldDocId 被复制文档
     * @param copyfile 是否复制附件信息
     * @param deleteaccessory 被删除附件
     * @param isNewDocEditionId 是否作为新的文档，即不作为原文档的新版本。
     * @param copyRight 是否复制权限
     * @param newStatus 新文档的状态，若为""则复制原来文档的状态
     * @param isLatestOnly 是否只复制最新版本的文档
     * @param copyReallyFile 是否复制附件文件
     */    
	private void copyDocToNewDoc(int oldDocId,boolean copyfile,String deleteaccessory,boolean isNewDocEditionId,boolean copyRight,String newStatus,boolean isLatestOnly,boolean copyReallyFile) throws Exception {
        copyDocToNewDoc(oldDocId,copyfile,deleteaccessory,isNewDocEditionId,copyRight,newStatus,isLatestOnly,copyReallyFile,true);
    }
     
    private void copyDocToNewDoc(int oldDocId,boolean copyfile,String deleteaccessory,boolean isNewDocEditionId,boolean copyRight,String newStatus,boolean isLatestOnly,boolean copyReallyFile,boolean updatereplydoc) throws Exception {
        DocViewer dv = new DocViewer();
        RecordSet rs = new RecordSet();
        RecordSet recorder = new RecordSet();

        int oldid = oldDocId;
        String dbtype = rs.getDBType();
        boolean isoracle = dbtype.equals("oracle");
        boolean ismysql = dbtype.equals(DBConstant.DB_TYPE_MYSQL);

        String sql = "";
        String sqllog = "";
        
        String docStatusString="docstatus";
        newStatus=Util.null2String(newStatus);
        if(newStatus.equals("'0'")||newStatus.equals("'1'")||newStatus.equals("'2'")||newStatus.equals("'3'")||newStatus.equals("'4'")||newStatus.equals("'5'")
         ||newStatus.equals("'6'")||newStatus.equals("'7'")||newStatus.equals("'8'")||newStatus.equals("'9'")){
        	docStatusString=newStatus;
        }
     
       
        if (isoracle || ismysql) {
            sql = "insert into DocDetail(" +
                    "id,maincategory,subcategory," +
                    "seccategory,doclangurage,docapprovable," +
                    "docreplyable,isreply,replydocid,docsubject,"
                    + "docpublishtype,itemid,itemmaincategoryid,hrmresid,crmid,projectid,"
                    + "financeid,doccreaterid,docdepartmentid,doccreatedate,doccreatetime,"
                    + "doclastmoduserid,doclastmoddate,doclastmodtime,docapproveuserid,"
                    + "docapprovedate,docapprovetime,docarchiveuserid,docarchivedate,"
                    + "docarchivetime,docstatus,parentids,assetid,ownerid,keyword,"
                    + "accessorycount,replaydoccount,usertype,doctype,cancopy,canremind,docextendname"
                    
                    + ",doccode,doceditionid,ishistory,approveType,readoptercanprint,invalidationdate,docvaliduserid,docvaliddate,docvalidtime,"
                    + "docpubuserid,docpubdate,docpubtime,docreopenuserid,docreopendate,docreopentime,"
                    + "docinvaluserid,docinvaldate,docinvaltime,doccanceluserid,doccanceldate,doccanceltime"
                    
                    +",docCreaterType,docLastModUserType,docApproveUserType,docValidUserType,docInvalUserType"
                    +",docArchiveUserType,docCancelUserType,docPubUserType,docReopenUserType,ownerType"
                    +",hasUsedTemplet"                   
                    +",canPrintedNum,editMouldId,orderable"    
                    +",secretLevel"
                    +",secretValidity"
                    +",replyremind"

                    + ") "
                    + "select " + this.id + "," + (this.maincategory==0?"maincategory":this.maincategory) + "," + (this.subcategory==0?"subcategory":this.subcategory) + "," + (this.seccategory==0?"seccategory":this.seccategory)
                    + ",doclangurage,docapprovable,docreplyable,isreply,replydocid,"
                    + "docsubject,docpublishtype,itemid,itemmaincategoryid,hrmresid,crmid,"
                    + "projectid,financeid,doccreaterid,docdepartmentid,doccreatedate,"
                    + "doccreatetime,doclastmoduserid,doclastmoddate,doclastmodtime,"
                    + "docapproveuserid,docapprovedate,docapprovetime,docarchiveuserid,"
                    + "docarchivedate,docarchivetime,"
                    //+ "'1',"
                    + docStatusString+","                    
                    + // docstatus
                    "parentids,assetid,ownerid,keyword,accessorycount,replaydoccount,"
                    + "usertype  ,doctype,cancopy,canremind,docextendname"
                    
                    + ",doccode,doceditionid,ishistory,approveType,readoptercanprint,invalidationdate,docvaliduserid,docvaliddate,docvalidtime,"
                    + "docpubuserid,docpubdate,docpubtime,docreopenuserid,docreopendate,docreopentime,"
                    + "docinvaluserid,docinvaldate,docinvaltime,doccanceluserid,doccanceldate,doccanceltime"
                    
                    +",docCreaterType,docLastModUserType,docApproveUserType,docValidUserType,docInvalUserType"
                    +",docArchiveUserType,docCancelUserType,docPubUserType,docReopenUserType,ownerType"
                    
                    +",hasUsedTemplet"                   
                    +",canPrintedNum,editMouldId,orderable"        
                    +",secretLevel"
                    +",secretValidity"
                    +",replyremind"

                    + " from DocDetail where id = "
                    + oldid;
            //writeLog(sql);
            rs.executeSql(sql);

            // 执行触发器docdetail_getpinyin
            DocTriggerUtils docTriggerUtils = new DocTriggerUtils();
            docTriggerUtils.docdetail_getpinyin(rs);
            sql = "insert into DocDetailContent(docid,doccontent) select " + this.id + ",doccontent "
                    + "from DocDetailContent where docid = " + oldid;
            //writeLog(sql);
            rs.executeSql(sql);
            sql = "insert into DocDummyDetail(catelogid,docid,importdate,importtime,publicdate,publictime,status) select catelogid,"+this.id
	      	  	+",importdate,importtime,publicdate,publictime,status from DocDummyDetail where docid="+oldDocId;
            rs.execute(sql);
        } else {
            sql = "insert into DocDetail(id,maincategory,subcategory,seccategory,doclangurage,"
                    + "docapprovable,docreplyable,isreply,replydocid,docsubject,doccontent,"
                    + "docpublishtype,itemid,itemmaincategoryid,hrmresid,crmid,projectid,"
                    + "financeid,doccreaterid,docdepartmentid,doccreatedate,doccreatetime,"
                    + "doclastmoduserid,doclastmoddate,doclastmodtime,docapproveuserid,"
                    + "docapprovedate,docapprovetime,docarchiveuserid,docarchivedate,"
                    + "docarchivetime,docstatus,parentids,assetid,ownerid,keyword,"
                    + "accessorycount,replaydoccount,usertype,doctype,cancopy,canremind,docextendname"
                    
                    + ",doccode,doceditionid,ishistory,approveType,readoptercanprint,invalidationdate,docvaliduserid,docvaliddate,docvalidtime,"
                    + "docpubuserid,docpubdate,docpubtime,docreopenuserid,docreopendate,docreopentime,"
                    + "docinvaluserid,docinvaldate,docinvaltime,doccanceluserid,doccanceldate,doccanceltime"
                    
                    +",docCreaterType,docLastModUserType,docApproveUserType,docValidUserType,docInvalUserType"
                    +",docArchiveUserType,docCancelUserType,docPubUserType,docReopenUserType,ownerType"   
                    
                    +",hasUsedTemplet"                      
                    +",canPrintedNum,editMouldId,orderable"   
                    +",secretLevel"
                    +",secretValidity"
                    +",replyremind"

                    + ") "
					+ "select " + this.id + "," + (this.maincategory==0?"maincategory":this.maincategory) + "," + (this.subcategory==0?"subcategory":this.subcategory) + "," + (this.seccategory==0?"seccategory":this.seccategory)
                    + ",doclangurage,docapprovable,docreplyable,isreply,replydocid,"
                    + "docsubject,doccontent,docpublishtype,itemid,itemmaincategoryid,"
                    + "hrmresid,crmid,projectid,financeid,doccreaterid,docdepartmentid,"
                    + "doccreatedate,doccreatetime,doclastmoduserid,doclastmoddate,doclastmodtime,"
                    + "docapproveuserid,docapprovedate,docapprovetime,docarchiveuserid,"
                    //+ "docarchivedate,docarchivetime,'1',"
                    + "docarchivedate,docarchivetime,"                    
                    + docStatusString+","                    
                    + // docstatus
                    "parentids,assetid,ownerid,keyword,accessorycount,replaydoccount,"
                    + "usertype ,doctype,cancopy,canremind,docextendname"
                    
                    + ",doccode,doceditionid,ishistory,approveType,readoptercanprint,invalidationdate,docvaliduserid,docvaliddate,docvalidtime,"
                    + "docpubuserid,docpubdate,docpubtime,docreopenuserid,docreopendate,docreopentime,"
                    + "docinvaluserid,docinvaldate,docinvaltime,doccanceluserid,doccanceldate,doccanceltime"
                    
                    +",docCreaterType,docLastModUserType,docApproveUserType,docValidUserType,docInvalUserType"
                    +",docArchiveUserType,docCancelUserType,docPubUserType,docReopenUserType,ownerType"                    
                    
                    +",hasUsedTemplet"                      
                    +",canPrintedNum,editMouldId,orderable"  
                    +",secretLevel"
                    +",secretValidity"
                    +",replyremind"

                    + " from DocDetail where id = " + oldid;
            //writeLog(sql);
            rs.executeSql(sql);
            // 执行触发器docdetail_getpinyin
            DocTriggerUtils docTriggerUtils = new DocTriggerUtils();
            docTriggerUtils.docdetail_getpinyin(rs);
            sql = "insert into DocDummyDetail(catelogid,docid,importdate,importtime,publicdate,publictime,status) select catelogid,"+this.id
		      	  +",importdate,importtime,publicdate,publictime,status from DocDummyDetail where docid="+oldDocId;
		    rs.execute(sql);
        }
        
        //copy主题图片
        rs.executeQuery("select themeshowpic from DocDetail where id=?",oldDocId);
        if(rs.next()){
        	int themeshowpic = rs.getInt("themeshowpic");
        	if(themeshowpic > 0){
        		int newthemeshowpic = ImageFileManager.copyImageFile(themeshowpic);
        		if(newthemeshowpic > 0){
        			rs.executeUpdate("update DocDetail set themeshowpic=? where id=?",newthemeshowpic,this.id);
        		}
        	}
        }
                
        RecordSet rsIn=new RecordSet(); //reply doc
        //rs.executeSql("select id,parentids from docdetail where ','+parentids+',' like '%,"+oldid+",%'");
        if(isoracle){
        	rs.executeSql("select id,parentids from docdetail where ','||parentids||',' like '%,"+oldid+",%'");       	
        }else{
        	rs.executeSql("select id,parentids from docdetail where ','+parentids+',' like '%,"+oldid+",%'");
        }
        while(rs.next()){        	
        	 String newParentids="";    
        	 String tempId=Util.null2String(rs.getString(1));
        	 String oldParentids=Util.null2String(rs.getString(2));
        	 
        	 ArrayList oPList=Util.TokenizerString(oldParentids, ",");
        	 for(int i=0;i<oPList.size();i++){
        		 String oP=(String)oPList.get(i);
        		 if(oP.equals(""+oldid)){
        			 newParentids+=this.id+",";
        		 } else {
        			 newParentids+=oP+",";
        		 }
        	 }
        	 if(!newParentids.equals("")) newParentids=newParentids.substring(0,newParentids.length()-1);
        	 String strNewSql="update docdetail set parentids='"+newParentids+"' where id="+tempId;
        	 rsIn.executeSql(strNewSql);        	 
        }
          
        
        
        if(isNewDocEditionId){
        	this.docEditionId=-1;
        	this.docEdition=-1;
            if(scc.isEditionOpen(this.seccategory)) {//如果版本管理开启
                this.docEditionId = this.getNextEditionId(rs);
                this.docEdition = 1;
            }
            rs.executeSql("update DocDetail set docEditionId="+this.docEditionId+",docEdition="+this.docEdition+" where id="+this.id);
        }
        
        dc.updateDocInfoCache("" + id);

        //替换文档正文中的图片链接为新生成的图片
        String contentSql = "";
        String newDocContent = "";
        if (isoracle || ismysql) {
            contentSql = "select doccontent from docdetailcontent where docid = ?";
        }else{
            contentSql = "select doccontent from docdetail where id = ?";
        }
        rs.executeQuery(contentSql,this.id);
        if(rs.next()){
            newDocContent = Util.null2String(rs.getString("doccontent"));
        }
        //加密串or非加密串
        List<String> oldFileidArr = getImgByContent(newDocContent);
		
        if(copyfile){
	        // 写文档附件信息
	
	        int imagefileid = 0;
	        String imagefilename = "";
	        String imagefiledesc = "";
	        int imagefilewidth = 0;
	        int imagefileheight = 0;
	        int imagefielsize = 0;
	        String docfiletype = "";
	        int imagefileused = 0;
	        String versionid = "";
	        String versionDetail = "";
	        String isextfile = "";
			String hasUsedTemplet = "";
	        int isaesencrypt = 0;
	        String aescode = "";
	        String operateuserid = "";
	        String operatedate  = "";
	        String operatetime  = "";

	        
	        String sqlstr = "select * from docimagefile where docid=" + oldid + " and imagefileid not in (select imagefiledesc from docimagefile where docid = -"+oldid+") ";
	        deleteaccessory=this.getAllDeleteaccessory(oldid,deleteaccessory);	        
	        if(deleteaccessory!=null&&!"".equals(deleteaccessory)){
	        	sqlstr+=" and imagefileid not in (" + deleteaccessory + ")";
	        }
	        //sqlstr+=" order by id asc,versionId desc ";
	        if(isLatestOnly){
	        	sqlstr+=" order by id asc,versionId desc ";
	        }else{
	        	sqlstr+=" order by id asc,versionId asc ";
	        }	        
	        //boolean hasFirst=false;
	        int oldDocImageFileId=0;
	        ArrayList oldDocImageFileIdList=new ArrayList();
	        Map docimagefileidMap=new HashMap();
			Map<String,String> oldFileidMap = new HashMap<>();
	        rs.executeSql(sqlstr);
			//用来记录html正文中的图片新生成的图片id
	        Map<String,String> newfileidmap = new HashMap<>();
	        while (rs.next()) {
	        	
	        	oldDocImageFileId = rs.getInt("id");
	        	if(isLatestOnly&&oldDocImageFileIdList.indexOf(""+oldDocImageFileId)>=0){
	        		continue;
	        	}
	        	
	            //int docimagefileid = imgManger.getNextDocImageFileId();
	        	int docimagefileid=Util.getIntValue((String)docimagefileidMap.get(""+oldDocImageFileId),-1);
	        	if(docimagefileid<=0){
	        		docimagefileid = imgManger.getNextDocImageFileId();
	        		docimagefileidMap.put(""+oldDocImageFileId,""+docimagefileid);
	        	}
	        	
        		RecordSet rs1 = new RecordSet();
				docfiletype = rs.getString("docfiletype");
	        	if(copyReallyFile){
	        		
	        		imagefileid = rs.getInt("imagefileid");
					int oldfileidval = imagefileid;
                	int imageid =ImageFileManager.copyImageFile(imagefileid);	                
	                if(imageid>0) {


						
//	            		rs1.executeProc("SequenceIndex_SelectVersionId", "");
//	            		if (rs1.next()) {
//	            			versionid = rs1.getString(1);
//	            		}
	                	versionid=""+versionIdUpdate.getVersionNewId();

	            		if(imageFileIdOfPicChangeList!=null){
		                	Map imageFileIdOfPicChangeMap=new HashMap();
		                	imageFileIdOfPicChangeMap.put("oldImageFileId",""+imagefileid);
		                	imageFileIdOfPicChangeMap.put("newImageFileId",""+imageid);		                	
		                	imageFileIdOfPicChangeList.add(imageFileIdOfPicChangeMap);
	            		}
	            		
	                	imagefileid = imageid;
	                }
					if("1".equals(docfiletype) || "11".equals(docfiletype)){
                       newfileidmap.put(oldfileidval+"",imagefileid+"");
                       for(int j=0;j<oldFileidArr.size();j++){
                           String fileidval = oldFileidArr.get(j);						  
                           if((""+oldfileidval).equals(DocDownloadCheckUtil.getDownloadfileidstr(fileidval))){
                               oldFileidMap.put(fileidval,imagefileid+"");
                           }
                       }
					  
                    }
	        	} else {
	        		imagefileid = rs.getInt("imagefileid");
	        		rs1.executeProc("imagefile_AddByDoc", "" + imagefileid);
	        		versionid = rs.getString("versionid");
	        	}
	
	            imagefilename = rs.getString("imagefilename");
	            imagefiledesc = rs.getString("imagefiledesc");
	            imagefilewidth = rs.getInt("imagefilewidth");
	            imagefileheight = rs.getInt("imagefileheight");
	            imagefielsize = rs.getInt("imagefielsize");
	            //docfiletype = rs.getString("docfiletype");
                operateuserid = Util.null2s(rs.getString("operateuserid"),"0");
                operatedate = rs.getString("operatedate");
                operatetime = rs.getString("operatetime");
	            //versionid = rs.getString("versionid");
	            versionDetail = rs.getString("versionDetail");
	            isextfile = Util.null2String(Util.getIntValue(rs.getString("isextfile"), 0)+"");
	            hasUsedTemplet = Util.null2String(Util.getIntValue(rs.getString("hasUsedTemplet"), 0)+"");	            
	            String tempsql = "insert into docimagefile(id,docid,imagefileid,imagefilename,imagefiledesc,"
	                    + "imagefilewidth,imagefileheight,imagefielsize,docfiletype,versionid,versionDetail,isextfile,hasUsedTemplet" +
                        " ,operateuserid,operatedate,operatetime) values("
	                    + docimagefileid + "," + id + "," + imagefileid + ",'" + Util.toHtml100(imagefilename) + "','" + Util.toHtml100(imagefiledesc)
	                    + "'," + imagefilewidth + "," + imagefileheight + "," + imagefielsize + ",'" + docfiletype + "','"
	                    + versionid + "','" + Util.toHtml100(versionDetail) + "', '"+isextfile+"', '"+hasUsedTemplet+"'" +
                        " ,"+operateuserid+", '"+operatedate+"','"+operatetime+"'" +")";
	            recorder.executeSql(tempsql);
	            
	            oldDocImageFileIdList.add(""+oldDocImageFileId);	            
	        }
			//遍历
            for (int i=0;i<oldFileidArr.size();i++){
	            String oldfileval1 = oldFileidArr.get(i);
	            String oldfilencodeval = DocDownloadCheckUtil.getDownloadfileidstr(oldfileval1);				
	            for (Map.Entry<String,String> entry : oldFileidMap.entrySet()){
					
	                if(entry.getKey().equals(oldfileval1) && entry.getKey().equals(oldfileval1)){                   
                        newDocContent = newDocContent.replaceAll(oldfileval1,entry.getValue());                     
                    }
                }
            }
            if (isoracle || ismysql) {               
                recorder.executeUpdate("update DocDetailContent set doccontent=? where docid=?", newDocContent, this.id);
            }else{
				recorder.executeUpdate("update DocDetail set doccontent=? where id=?",newDocContent,""+this.id);
			}			
        }
      if(copyRight){    
        // 写文档共享信息
        rs.executeProc("DocShare_SelectByDocId", "" + oldid);
        while (rs.next()) {
            String ProcPara = "";
            char flag = 2;
            String docid = "" + this.id;
            String sharetype = Util.null2String(rs.getString("sharetype"));
            String seclevel = Util.null2String(rs.getString("seclevel"));
            String rolelevel = Util.null2String(rs.getString("rolelevel"));
            String sharelevel = Util.null2String(rs.getString("sharelevel"));
            String userid = Util.null2String(rs.getString("userid"));
            String subcompanyid = Util.null2String(rs.getString("subcompanyid"));
            String departmentid = Util.null2String(rs.getString("departmentid"));
            String roleid = Util.null2String(rs.getString("roleid"));
            String foralluser = Util.null2String(rs.getString("foralluser"));
            String crmid = Util.null2String(rs.getString("crmid"));
            String orgGroupId = Util.null2String(rs.getString("orgGroupId"));

            String sharesource = Util.null2String(rs.getString("sharesource"));           
            String isSecDefaultShare = Util.null2String(rs.getString("isSecDefaultShare"));


			int orgid = Util.getIntValue(rs.getString("orgid"),0);
			int seclevelmax = Util.getIntValue(rs.getString("seclevelmax"),255);
			int includesub = Util.getIntValue(rs.getString("includesub"),0);
			int allmanagers = Util.getIntValue(rs.getString("allmanagers"),0);

			    String joblevel=Util.getIntValue(rs.getString("joblevel"),0)+"";
				String jobdepartment=Util.getIntValue(rs.getString("jobdepartment"),0)+"";
				String jobsubcompany=Util.getIntValue(rs.getString("jobsubcompany"),0)+"";
				String jobids=Util.getIntValue(rs.getString("jobids"),0)+"";
				

            ProcPara = docid;
            ProcPara += flag + sharetype;
            ProcPara += flag + seclevel;
            ProcPara += flag + rolelevel;
            ProcPara += flag + sharelevel;
            ProcPara += flag + userid;
            ProcPara += flag + subcompanyid;
            ProcPara += flag + departmentid;
            ProcPara += flag + roleid;
            ProcPara += flag + foralluser;
            ProcPara += flag + crmid; // CRMID
            ProcPara += flag + orgGroupId; // orgGroupId

            //recorder.executeProc("DocShare_IFromDocSecCategory", ProcPara);
            /** TD12005  =========文档下载权限 开始=============*/
            String downloadlevel = String.valueOf(Util.getIntValue(rs.getString("downloadlevel"), 0));//TD12005
            ProcPara += flag + downloadlevel; // 文档下载权限
            /** TD12005  =========文档下载权限 结束=============*/
            recorder.executeProc("DocShare_IFromDocSecCat_G", ProcPara);            
            
            if (!"".equals(isSecDefaultShare)) {
            	if(recorder.next()){
            		String newid = Util.null2String(recorder.getString(1));
            		RecordSet tmpcopyrs = new RecordSet();
            		tmpcopyrs.executeSql("update docshare set isSecDefaultShare=" + isSecDefaultShare + ",allmanagers='"+allmanagers+"',includesub='"+includesub+"', orgid='"+orgid+"',seclevelmax='"+seclevelmax+"',joblevel='"+joblevel+"',jobdepartment='"+jobdepartment+"',jobsubcompany='"+jobsubcompany+"',jobids='"+jobids+"' where id="
                        + newid);
					if(!"".equals(sharesource)){
                		tmpcopyrs.executeSql("update docshare set sharesource="+sharesource+" where id="+ newid);
            		}	
            	}
            }else{

				if(recorder.next()){
            		String newid = Util.null2String(recorder.getString(1));
            		RecordSet tmpcopyrs = new RecordSet();
            		tmpcopyrs.executeSql("update docshare set allmanagers='"+allmanagers+"',includesub='"+includesub+"', orgid='"+orgid+"',seclevelmax='"+seclevelmax+"',joblevel='"+joblevel+"',jobdepartment='"+jobdepartment+"',jobsubcompany='"+jobsubcompany+"',jobids='"+jobids+"' where id="
                        + newid);
					if(!"".equals(sharesource)){
                		tmpcopyrs.executeSql("update docshare set sharesource="+sharesource+" where id="+ newid);
            		}	
            	}
			
			
			
			}
                    
            
        }
        dv.setDocShareByDoc("" + this.id);
      }

      //复制自定义信息
      if(customDataIdMapping==null || customDataIdMapping.length == 0) {
	      CustomFieldManager cfm = new CustomFieldManager("DocCustomFieldBySecCategory", this.seccategory);
	      cfm.getCustomFields();
	      String nameStr = "";
	      while (cfm.next()) {
	          nameStr += "," + cfm.getFieldName(""+cfm.getId());
	      }       
	      if (!nameStr.equals("")) {
	          nameStr = nameStr.substring(1);
	
	          sql = "insert into cus_fielddata(scope,scopeid,id," + nameStr + ") "
	               +" select 'DocCustomFieldBySecCategory'," + this.seccategory + "," + this.id+ "," + nameStr 
	               + "  from cus_fielddata where scope='DocCustomFieldBySecCategory'  and id="+oldid;
	           //System.out.println("sql = " + sql);//test
	          rs.executeSql(sql);
	      }
      } else {
	        String srcNameStr = "";
      	    List srcNameList=new ArrayList();
    	    int srcFieldId=-1;
    	    String srcFieldValue=null;
    	    String srcFieldShowName=null;
	      
	        String objNameStr = "";
        	List objNameList=new ArrayList();
        	int objFieldId=-1;
        	String objFieldValue=null;            	
            String cusFieldDataObjSql=null;
            String cusFieldDataObjStr="";
            
        	Map objNameSrcNameMap=new HashMap();
        	Map srcFieldValueAndFieldShowNameMap=null;
	        RecordSet rsCus=new RecordSet();
			//customDataIdMapping = removedouble(customDataIdMapping);
	        for(int i=0;i<customDataIdMapping.length;i++){
	    	    List ids = Util.TokenizerString(customDataIdMapping[i], "_");
				rsCus.execute("select fieldname from cus_formdict where id="+ids.get(0));
				if(rsCus.next()){
					srcNameStr += ","+rsCus.getString("fieldname");
				}
				rsCus.execute("select fieldname from cus_formdict where id="+ids.get(1));
				if(rsCus.next()){
					objNameStr += ","+rsCus.getString("fieldname");
				}
	    	    //srcNameStr += ",field" + ids.get(0);
	    	    //objNameStr += ",field" + ids.get(1);
	    	    
        		objNameSrcNameMap.put(""+ids.get(1),""+ids.get(0));
        		srcNameList.add(""+ids.get(0));
        		objNameList.add(""+ids.get(1));	    	    
	        }
	      
	        if (!srcNameStr.equals("")&&!objNameStr.equals("")) {
	    	    srcNameStr = srcNameStr.substring(1);
	    	    objNameStr = objNameStr.substring(1);
	    	    
            	RecordSet rsTemp=new RecordSet();	    	    
            	String fieldDbType=null;
            	String fieldHtmlType=null;
				String fieldName=null;

                int fieldLength=0;            	
            	Map fieldHtmlTypeMap=new HashMap();
            	
            	Map cusFormDictDataMap=new HashMap();	
				rs.executeSql("select id,fieldDbType,fieldHtmlType,type,fieldname from cus_formdict");

	            while(rs.next()){
	            	cusFormDictDataMap.put("fieldDbType"+Util.null2String(rs.getString("id")),Util.null2String(rs.getString("fieldDbType")));
	            	cusFormDictDataMap.put("fieldHtmlType"+Util.null2String(rs.getString("id")),Util.null2String(rs.getString("fieldHtmlType")));
	            	cusFormDictDataMap.put("type"+Util.null2String(rs.getString("id")),Util.null2String(rs.getString("type")));	            	
					cusFormDictDataMap.put("fieldName"+Util.null2String(rs.getString("id")),Util.null2String(rs.getString("fieldname")));	            	
	            }
	            
            	srcFieldValueAndFieldShowNameMap=new HashMap();
            	cusFieldDataObjSql="insert into cus_fielddata";
            	cusFieldDataObjStr="";
            	
            	int oldSecCategoryId=-1;
            	rs.executeSql("select secCategory from DocDetail where id=" + oldid);
            	if(rs.next()){
            		oldSecCategoryId=Util.getIntValue(rs.getString("secCategory"),-1);
            	}
            		
            	rs.executeSql("select "+srcNameStr+" from cus_fielddata where scope='DocCustomFieldBySecCategory' and scopeId="+oldSecCategoryId+" and id=" + oldid);
            	if(rs.next()){
            		for(int i=0;i<srcNameList.size();i++){
            			srcFieldId=Util.getIntValue((String)srcNameList.get(i),-1);
            			srcFieldValue=Util.null2String(rs.getString(i+1));
            			srcFieldShowName="";
            			fieldDbType=Util.null2String((String)cusFormDictDataMap.get("fieldDbType"+srcFieldId));	            			
            			fieldHtmlType=Util.null2String((String)cusFormDictDataMap.get("fieldHtmlType"+srcFieldId));
            		    fieldName=Util.null2String((String)cusFormDictDataMap.get("fieldName"+srcFieldId));
						if(fieldHtmlType.equals("5")){
                    		rsTemp.executeSql("  select selectName from cus_selectitem where fieldId="+srcFieldId+" and selectValue="+srcFieldValue);
                    		if(rsTemp.next()){
                    			srcFieldShowName=Util.null2String(rsTemp.getString("selectName"));
                    			srcFieldValueAndFieldShowNameMap.put("srcFieldShowName"+srcFieldId,srcFieldShowName);           			
                    		}	            				
            			}
            			srcFieldValueAndFieldShowNameMap.put("srcFieldValue"+srcFieldId,srcFieldValue);
            			                			
            		}
	            }
            	
            	for(int i=0;i<objNameList.size();i++){
        			objFieldId=Util.getIntValue((String)objNameList.get(i),-1);
        			srcFieldId=Util.getIntValue((String)objNameSrcNameMap.get(""+objFieldId));
        			srcFieldShowName=Util.null2String((String)srcFieldValueAndFieldShowNameMap.get("srcFieldShowName"+srcFieldId));           			
        			objFieldValue=Util.null2String((String)srcFieldValueAndFieldShowNameMap.get("srcFieldValue"+srcFieldId));

        			fieldDbType=Util.null2String((String)cusFormDictDataMap.get("fieldDbType"+objFieldId));	            			
        			fieldHtmlType=Util.null2String((String)cusFormDictDataMap.get("fieldHtmlType"+objFieldId));
        			
                    if (fieldDbType.startsWith("text") || fieldDbType.startsWith("char")|| fieldDbType.startsWith("varchar")|| fieldDbType.startsWith("browser")) {
                		if(fieldDbType.indexOf("(")>=0&&fieldDbType.indexOf(")")>fieldDbType.indexOf("(")+1){
                			fieldLength=Util.getIntValue(fieldDbType.substring(fieldDbType.indexOf("(")+1,fieldDbType.indexOf(")")),0);
                		}
                		if(fieldLength>0){
                			cusFieldDataObjStr += ",'" + Util.toHtml100(interceptString(objFieldValue,fieldLength)) + "'";
                		}else{
                			cusFieldDataObjStr += ",'" + Util.toHtml100(objFieldValue) + "'";
                		}
                    } else {
                    	if(fieldHtmlType.equals("5")){
                    		objFieldValue=this.getNewSelectValue(srcFieldShowName,objFieldValue,objFieldId);
                    	}
                    	cusFieldDataObjStr += ","+Util.getIntValue(objFieldValue,-1);
                    }            			
        			
            	}	            	
                
                if (!cusFieldDataObjStr.equals("")) {
                	cusFieldDataObjStr = cusFieldDataObjStr.substring(1);
                	cusFieldDataObjSql += "(scope,scopeid,id," + objNameStr + ") values('DocCustomFieldBySecCategory'," + this.seccategory + "," + this.id
                    + "," + cusFieldDataObjStr + ")";           
                    rs.executeSql(cusFieldDataObjSql);
                }	     
	        }
      }
    }
    
    public static String[] removedouble(String[] arrStr) {
        String[] result = null;
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < arrStr.length; i++) {
            if (!list.contains(arrStr[i])) {
                list.add(arrStr[i]);
            }
        }
        // 返回一个包含所有对象的指定类型的数组
        if (list.size() >= 1) {
            result =  list.toArray(new String[1]);
        }
        return result;
    }
    public static List<String> getImgByContent(String content){
        List<String> lists = new ArrayList<String>();
        List<String> resultLists = new ArrayList<String>();

        if(content == null || content.isEmpty()) return lists;


        String reg = "/weaver/weaver.file.FileDownload\\?fileid=([0-9A-Za-z]+)";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(content);
        while(matcher.find()){
            lists.add(matcher.group());
        }
        for (int i=0;i<lists.size();i++){
            String liststr = lists.get(i);
            String reg1 = "/weaver/weaver.file.FileDownload\\?fileid=([0-9A-Za-z]+)";
            Pattern pattern1 = Pattern.compile(reg1);
            Matcher matcher1 = pattern1.matcher(liststr);
            while(matcher1.find()){
                ArrayList list=Util.matchAll(matcher1.group(),"/weaver/weaver.file.FileDownload\\?fileid=([A-Za-z0-9]+)",1,1);
                String val1 = Util.null2String((String) list.get(0));
                resultLists.add(val1);
            }

        }
        return resultLists;
    }
    
    /**
     * 为文档添加新版本
     * @param oldDocId 旧文档ID
     * @param deleteaccessory 需要在新版本中删除的附件
     * @throws Exception
     */
    public void addNewDocForEdition(int oldDocId) throws Exception {
    	addNewDocForEdition(oldDocId,"");
    }

    public void addNewDocForEdition(int oldDocId,String deleteaccessory) throws Exception {
    	copyDocToNewDoc(oldDocId,deleteaccessory,true,true);
    	
    	RecordSet rs = new RecordSet();
    	rs.executeSql(" update docimagefile set imagefiledesc = '' where docid = -" + oldDocId);

    	rs.executeSql(" update docimagefile set docid = " + this.id + " where docid = -" + oldDocId);
//    	更新附件数 isextfile = '1' 是附件条件 TD8782
    	rs.executeSql("update docdetail set accessorycount = (select count(distinct id) from DocImageFile where isextfile = '1' and docid = " + this.id + " and docfiletype <> '1'   and docfiletype <> '11') where id = " + this.id);
        
        log.resetParameter();
        log.setDocId(this.id);
        log.setDocSubject(this.docsubject);
        log.setOperateType("16");
        log.setOperateUserid(userid);
        log.setUsertype(this.usertype);
        log.setClientAddress(this.clientip);
        log.setDocCreater(this.doccreaterid);
        log.setCreatertype(this.docCreaterType);       
        log.setDocLogInfo();
        
    }
    
    

    /**
     * 存储文档内容
     * 
     * @param request 一个HttpServletRequest对象存储了文档地所有信息
     * @return 文档的操作类型
     * @throws Exception 抛出异常
     */
    public String UploadDoc(HttpServletRequest request) throws Exception {

        String opera = "";
        String docmain = "";
        RecordSet rsSql = new RecordSet();

        try {
            FileUpload fu = new FileUpload(request);

            this.fileUpload=fu;
            
            // add by 王金永
            // 1 代表html类型；2代表 world 或者 excel 类型
            opera = fu.getParameter("operation");

            this.urlfrom = Util.null2String(fu.getParameter("urlfrom"));
            
            this.source = Util.null2String(fu.getParameter("source"));
           
            // 新建时候的进行的操作
            if (opera.equals("addsave") || opera.equals("adddraft") || opera.equals("addpreview")) {
                
                addDoc(fu,opera);

            } else if (opera.equals("editsave") || opera.equals("editdraft") || opera.equals("editpreview")) {
            
                editDoc(fu,opera);
            
            } else if (opera.equals("publish")) {
            
                publishDoc(fu);
            
            } else if (opera.equals("invalidate")) {
                
                invalidateDoc(fu);

            } else if (opera.equals("archive")) {

                archiveDoc(fu);
                
            } else if (opera.equals("cancel")) {

                cancelDoc(fu);
                
            } else if (opera.equals("reopen")) {

                reopenDoc(fu);
                
            } else if (opera.equals("reload")) {
                // 刷新时进行的操作
                this.id = Util.getIntValue(fu.getParameter("id"), 0);
                this.docsubject = fu.getParameter("docsubject");
                this.docsubject = interceptString(this.docsubject,400);                
                //this.docapprovable = Util.null2String(fu.getParameter("docapprovable"));
                //if (docapprovable.equals("1")) {
                if(scc.needApprove(this.seccategory)) {//如果需要审批
                    this.docstatus = "2";
                } else {
                    this.docstatus = "1";
                }

                ReloadDocInfo();
            /*
            } else if (opera.equals("reopen")) {
                // 从新打开时进行的操作
                this.id = Util.getIntValue(fu.getParameter("id"), 0);
                this.docsubject = fu.getParameter("docsubject");

                this.docstatus = "0";

                ReopenDocInfo();
            */
            } else if (opera.equals("delete")) {
            	RecordSet rs_del=new RecordSet();
            	int docsrecycle=0;
            	rs_del.executeSql("select propvalue from doc_prop where propkey='docsrecycle' ");
            	if(rs_del.next()){
            		docsrecycle=rs_del.getInt("propvalue");
            	}
            	User recycleuser=new User(userid);
            	if(docsrecycle==1&&"1".equals(recycleuser.getLogintype())){//开启回收站
            		this.id = Util.getIntValue(fu.getParameter("id"), 0);
            		DocRecycleManager docRecycleManager=new DocRecycleManager();
            		docRecycleManager.moveDocToRecycle(userid, this.usertype, this.id, this.clientip);
            	}else{
                // 删除此文档的操作
                this.id = Util.getIntValue(fu.getParameter("id"), 0);

                // add by wjy for delete custom data
                deleteCustomData(this.id);

                /* 需要注意删除该文档所有图片时候的情况 */

                imgManger.resetParameter();
                imgManger.setDocid(this.id);
                imgManger.DeleteAllDocImageInfo();

                this.docsubject = fu.getParameter("docsubject");
                this.docsubject = interceptString(this.docsubject,400);
                
                this.doccontent = Util.fromBaseEncoding(fu.getParameter("doccontent"), languageid);
                this.doccontent =Util.htmlFilter4UTF8(this.doccontent );
                
                //DeleteReplayDocCount(); // 需对前级文档的回复文档记录数减1，才可删此文档（DeleteDocInfo()实现）
                DeleteDocInfo();
                deleteHrmContract();
            	}

            } else if (opera.equals("delpic")) {
                // 删除图片时进行的操作
                this.id = Util.getIntValue(fu.getParameter("id"), 0);
                int imgid = Util.getIntValue(Util.getFileidOut(fu.getParameter("delimgid")), 0);
                String sql = "delete from docimagefile where imagefileid=" + imgid + " and docid = " + this.id;
                rsSql.executeSql(sql);

                imgManger.resetParameter();
                imgManger.setImagefileid(imgid);
                imgManger.setDocid(this.id);
                imgManger.DeleteSingleDocImageInfo();
                //更新附件数 isextfile = '1' 是附件条件 TD8782
                rsSql.executeSql("update docdetail set accessorycount = (select count(distinct id) from DocImageFile where isextfile = '1' and docid = " + this.id + " and docfiletype <> '1'   and docfiletype <> '11') where id = " + this.id);
                
            }else if(opera.equals("checkOut")){
            	//签出
                this.id = Util.getIntValue(fu.getParameter("id"), 0);
                
                rsSql.executeSql("select 1 from DocDetail  where id="+this.id+" and ((checkOutStatus<>'1' and checkOutStatus<>'2')or checkOutStatus is null)");
                if(!rsSql.next()){
                	return opera;
                }
                
                
                Calendar today = Calendar.getInstance();
                String formatDate = Util.add0(today.get(Calendar.YEAR), 4) + "-"
                        + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-"
                        + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);
                String formatTime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":"
                        + Util.add0(today.get(Calendar.MINUTE), 2) + ":" + Util.add0(today.get(Calendar.SECOND), 2);                
                //rs.executeSql("update  DocDetail set checkOutStatus='1',checkOutUserId="+this.userid+",checkOutUserType='"+this.usertype+"',checkOutDate='"+formatDate+"',checkOutTime='"+formatTime+"' where id="+this.id);
                rsSql.executeSql("update  DocDetail set checkOutStatus='2',checkOutUserId="+this.userid+",checkOutUserType='"+this.usertype+"',checkOutDate='"+formatDate+"',checkOutTime='"+formatTime+"' where id="+this.id);

                this.opreateType = Util.null2String(fu.getParameter("opreateType"));//1:内部   2:外部
                if ("".equals(opreateType)) {
                    this.opreateType = this.usertype;
                }
                rsSql.executeSql("select docSubject,docCreaterId,docCreaterType from DocDetail where id="+this.id);
                if(rsSql.next()){
                	this.docsubject=Util.null2String(rsSql.getString("docSubject"));
                    this.docsubject = interceptString(this.docsubject,400);                	
                	this.doccreaterid=Util.getIntValue(rsSql.getString("docCreaterId"),0);
                	docCreaterType=Util.null2String(rsSql.getString("docCreaterType"));            	
                }                
                log.resetParameter();
                log.setDocId(this.id);
                log.setDocSubject(this.docsubject);
                log.setOperateType("17");
                log.setOperateUserid(userid);
                log.setUsertype(this.opreateType);
                log.setClientAddress(this.clientip);
                log.setDocCreater(this.doccreaterid);
                log.setCreatertype(this.docCreaterType);
                log.setDocLogInfo();                 
            }else if(opera.equals("checkIn")){
            	//签入
                this.id = Util.getIntValue(fu.getParameter("id"), 0); 
                
                rsSql.executeSql("select 1 from DocDetail  where id="+this.id+" and (checkOutStatus='1' or checkOutStatus='2')");
                if(!rsSql.next()){
                	return opera;
                }
                
                rsSql.executeSql("update  DocDetail set checkOutStatus='0',checkOutUserId=-1,checkOutUserType='',checkOutDate='',checkOutTime='' where id ="+this.id);

                this.opreateType = Util.null2String(fu.getParameter("opreateType"));//1:内部   2:外部
                if ("".equals(opreateType)) {
                    this.opreateType = this.usertype;
                }
                rsSql.executeSql("select docSubject,docCreaterId,docCreaterType from DocDetail where id="+this.id);
                if(rsSql.next()){
                	this.docsubject=Util.null2String(rsSql.getString("docSubject"));
                    this.docsubject = interceptString(this.docsubject,400);               	
                	this.doccreaterid=Util.getIntValue(rsSql.getString("docCreaterId"),0);
                	docCreaterType=Util.null2String(rsSql.getString("docCreaterType"));            	
                }                
            	log.resetParameter();
                log.setDocId(this.id);
                log.setDocSubject(this.docsubject);
                log.setOperateType("19");
                log.setOperateUserid(userid);
                log.setUsertype(this.opreateType);
                log.setClientAddress(this.clientip);
                log.setDocCreater(this.doccreaterid);
                log.setCreatertype(this.docCreaterType);
                log.setDocLogInfo();              	
            }else if(opera.equals("useTemplet")){
            	//套红
                this.id = Util.getIntValue(fu.getParameter("id"), 0);
                this.topage = Util.null2String(fu.getParameter("topage"));
                this.docstatus = fu.getParameter("docstatus");
            	this.oldstatus = docstatus;
            	editDoc(fu,opera);
            	rsSql.executeSql("update  DocDetail set hasUsedTemplet='1' where id ="+this.id);
            	//rs.executeSql("update  docimagefile set docId=-docId where docId<0 and docId=-"+this.id);           	
            }
            
            
            // 判断新建的是不是个人文档
            String from = Util.null2String(fu.getParameter("from"));
            String userId = Util.null2String(fu.getParameter("userId"));
            if ("personalDoc".equals(from)) {
                DocUserSelfUtil dusu = new DocUserSelfUtil();
                String userCatalogId = Util.null2String(fu.getParameter("userCategory"));
                String userType = Util.null2String(fu.getParameter("userType"));
                
                if(opera.equals("addsave")){
                    // 修改表DocUserselfDocs
                    String strSql = "insert into DocUserselfDocs (docid,usercatalogid,userid,doctype,usertype) values ("
                            + id + "," + userCatalogId + "," + userId + "," + docType + "," + userType + ")";
                    rsSql.executeSql(strSql);
                    dusu.writDocShare("" + id, userId, userType, "2");                    
                }

                setUserCatalogId(userCatalogId);
                opera = "addPersonalDoc";
            }
        } catch (Exception e) {
            writeLog(e);
            return opera + "_1";
        }
        // 返回进行的操作类型
        return opera;

    }

    /**
     * 存储文档内容
     * 
     * @param fu 一个FileUpload对象存储了文档地所有信息
     * @param createrid 创建者ID
     * @param doccontent 文档内容
     * @param userneed 附件个数
     * @return 文档的操作类型
     * @throws Exception
     */
    public String UploadDocHtmlAndFile(FileUpload fu, int createrid, String doccontent, int userneed) throws Exception {
        String opera = "";
        String docmain = "";
        RecordSet rsSql = new RecordSet();
        ResourceComInfo rc = new ResourceComInfo();
        try {

            this.id = getNextDocId(rsSql);
            int accessorynum = userneed;
            String[] needuploads = new String[accessorynum];

            for (int i = 0; i < accessorynum; i++) {
                needuploads[i] = "accessory" + (i + 1);
            }

            String[] fileids = fu.uploadFiles(needuploads);
            String[] filenames = fu.getFileNames();

            int accessorynumtrue = 0;

            for (int i = 0; i < accessorynum; i++) {
                if (Util.getIntValue(fileids[i], 0) == 0)
                    continue;
                accessorynumtrue++;
                imgManger.resetParameter();
                imgManger.setDocid(this.id);
                imgManger.setImagefileid(Util.getIntValue(fileids[i], 0));
                imgManger.setImagefilename(filenames[i]);
                imgManger.setDocfiletype("2");
                imgManger.setIsextfile("1");
                imgManger.AddDocImageInfo();
            }

            int docimages_num = Util.getIntValue(fu.getParameter("docimages_num"), 0);

            needuploads = new String[docimages_num];
            for (int i = 0; i < docimages_num; i++) {
                needuploads[i] = "docimages_" + i;
            }

            fileids = fu.uploadFiles(needuploads);
            filenames = fu.getFileNames();
            for (int i = 0; i < docimages_num; i++) {
                if (Util.getIntValue(fileids[i], 0) == 0)
                    continue;
                imgManger.resetParameter();
                imgManger.setDocid(this.id);
                imgManger.setImagefileid(Util.getIntValue(fileids[i], 0));
                imgManger.setImagefilename(filenames[i]);
                imgManger.setDocfiletype("1");
                imgManger.AddDocImageInfo();
            }

            int tmppos = doccontent.indexOf("src=");
            while (tmppos != -1) {
                int startpos = doccontent.indexOf("\"", tmppos);
                int endpos = doccontent.indexOf("\"", startpos + 1);
                String tempStr = doccontent.substring(startpos + 1, endpos);

                for (int i = 1; i < docimages_num; i++) {
                    if (tempStr.indexOf(filenames[i]) != -1) {
                        String replaceStr = weaver.general.GCONST.getContextPath()+"/weaver/weaver.file.FileDownload?fileid=" + fileids[i];
                        doccontent = Util.StringReplace(doccontent, tempStr, replaceStr);

                    }
                }

                tmppos = doccontent.indexOf("src=", endpos);
            }

            doccontent = Util.toScreen(doccontent, 7, "0");
            // System.out.println("doccontent" + doccontent) ;

            Calendar today = Calendar.getInstance();
            String formatdate = Util.add0(today.get(Calendar.YEAR), 4) + "-"
                    + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-"
                    + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);
            String formattime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":"
                    + Util.add0(today.get(Calendar.MINUTE), 2) + ":" + Util.add0(today.get(Calendar.SECOND), 2);

            this.maincategory = Util.getIntValue(fu.getParameter("mainCatoryid"), 0);
            this.subcategory = Util.getIntValue(fu.getParameter("subCatoryid"), 0);
            this.seccategory = Util.getIntValue(fu.getParameter("secCatoryid"), 0);
            this.doclangurage = 7;
            this.docapprovable = "0";
            this.docreplyable = fu.getParameter("docreplyable");
            this.isreply = Util.null2String(fu.getParameter("isreply"));
            this.replydocid = Util.getIntValue(fu.getParameter("replydocid"), 0);
            this.docsubject = fu.getParameter("docSubject");
            this.docsubject = interceptString(this.docsubject,400);           
            this.doccontent = doccontent;
            this.docpublishtype = "0";
            if (docpublishtype.equals("2")) {
                //docmain = fu.getParameter("docmain");
            	docmain = Util.toHtml2(Util.encodeAnd(Util.null2String(fu.getParameter("docmain"))));            	
                this.doccontent = docmain + "!@#$%^&*" + this.doccontent;
            }

            this.itemid = Util.getIntValue(fu.getParameter("itemid"), 0);
            this.itemmaincategoryid = Util.getIntValue(fu.getParameter("itemmaincategoryid"), 0);
            this.hrmresid = Util.getIntValue(fu.getParameter("hrmresid"), 0);
            this.assetid = Util.getIntValue(fu.getParameter("assetid"), 0);
            this.ownerid = createrid;
            this.crmid = Util.getIntValue(fu.getParameter("crmid"), 0);
            this.projectid = Util.getIntValue(fu.getParameter("projectid"), 0);
            this.financeid = Util.getIntValue(fu.getParameter("financeid"), 0);
            this.doccreaterid = createrid;
            this.docdepartmentid = Util.getIntValue(rc.getDepartmentID("" + createrid), 0);
            this.doccreatedate = formatdate;
            this.doccreatetime = formattime;
            this.doclastmoduserid = this.userid;
            this.doclastmoddate = formatdate;
            this.doclastmodtime = formattime;
            this.docapproveuserid = 0;
            this.docapprovedate = "";
            this.docapprovetime = "";
            this.docarchiveuserid = 0;
            this.docarchivedate = "";
            this.docarchivetime = "";

            this.docstatus = Util.null2String(fu.getParameter("docStatus"));

            if (Util.null2String(fu.getParameter("parentids")).equals("")) {
                this.parentids = this.id + "";
            } else
                this.parentids = Util.null2String(fu.getParameter("parentids")) + "," + this.id;

            this.keyword = Util.null2String(fu.getParameter("keyword"));
            /* 文档的关键字 */

            int docid = this.id;

            this.accessorycount = accessorynumtrue;

            if (isreply.equals("1")) {
                AddReplayDocCount(rsSql); // 修改回复记录条数
            }

            this.replaydoccount = 0; /* 回复文档总数 */
            this.usertype = "1"; /* 创建的用户类型 1: 内部 2: 外部 */
            this.topage = Util.null2String(fu.getParameter("topage"));

            this.contractman = Util.null2String(fu.getParameter("contractman"));
            this.contractstartdate = Util.null2String(fu.getParameter("contractstartdate"));
            this.contractenddate = Util.null2String(fu.getParameter("contractenddate"));
            this.docmodule = Util.null2String(fu.getParameter("docmodule"));
            this.proenddate = Util.null2String(fu.getParameter("proenddate"));
            this.typeid = Util.getIntValue(fu.getParameter("typeid"), 0);
            this.urlfrom = Util.null2String(fu.getParameter("urlfrom"));
            this.orderable = "" + scc.getSecOrderable(this.seccategory);
            AddDocInfo();
            AddShareInfo();
            if (!contractman.equals("")) {
                addHrmContract();
            }

            String note = Util.null2String(fu.getParameter("note"));
            String sql_note = "update docdetail set note = '" + note + "' where id =" + id;
            rsSql.executeSql(sql_note);

            DocViewer DocViewer = new DocViewer();
            DocViewer.setDocShareByDoc("" + id);

        } catch (Exception e) {
            writeLog(e);
            return "err_Exception";
        }

        return "err_uploadSuccess";

    }

    /**
     * 存储文档内容
     * 
     * @param fu 一个FileUpload对象存储了文档地所有信息
     * @param docid_html 文档ID
     */
    public void UploadImage(FileUpload fu, String docid_html) {

        String opera = "";
        String doccontent = " ";
        String docmain = "";
        String newdoccontent = "";
        // rs = new RecordSet();

        int docimages_num = Util.getIntValue(fu.getParameter("docimages_num"), 0);
        this.id = Util.getIntValue(docid_html);
        String[] needuploads = new String[docimages_num];
        for (int i = 0; i < docimages_num; i++) {
            needuploads[i] = "docimages_" + i;
        }

        String[] fileids = fu.uploadFiles(needuploads);
        String[] filenames = fu.getFileNames();
        for (int i = 0; i < docimages_num; i++) {
            if (Util.getIntValue(fileids[i], 0) == 0)
                continue;
            imgManger.resetParameter();
            imgManger.setDocid(this.id);
            imgManger.setImagefileid(Util.getIntValue(fileids[i], 0));
            imgManger.setImagefilename(filenames[i]);
            imgManger.setDocfiletype("1");
            imgManger.AddDocImageInfo();
        }
    }

    /**
     * 存储文档内容
     * 
     * @param fu 一个FileUpload对象存储了文档地所有信息
     * @param createrid 创建者ID
     * @return 文档的操作类型
     * @throws Exception
     */
    public String UploadDoc(FileUpload fu, int createrid) throws Exception {

        String opera = "";
        String docmain = "";
        RecordSet rsSql = new RecordSet();

        try {
            opera = fu.getParameter("operation");

            if (opera.equals("addsave") || opera.equals("adddraft")) {

                this.id = getNextDocId(rsSql);

                int accessorynum = Util.getIntValue(fu.getParameter("accessorynum"), 1);

                String filenames;
                String fileids;
                fileids = fu.uploadFiles("accessory1");
                filenames = fu.getFileName();

                int accessorynumtrue = 0;

                for (int i = 0; i < accessorynum; i++) {
                    if (Util.getIntValue(fileids, 0) == 0)
                        continue;
                    accessorynumtrue++;
                    imgManger.resetParameter();
                    imgManger.setDocid(this.id);
                    imgManger.setImagefileid(Util.getIntValue(fileids, 0));
                    imgManger.setImagefilename(filenames);
                    imgManger.setDocfiletype("2");
                    imgManger.setIsextfile("1");
                    imgManger.AddDocImageInfo();
                }

                this.doccontent = Util.fromBaseEncoding(fu.getParameter("doccontent"), languageid);
                this.doccontent =Util.htmlFilter4UTF8(this.doccontent );
                
                Calendar today = Calendar.getInstance();
                String formatdate = Util.add0(today.get(Calendar.YEAR), 4) + "-"
                        + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-"
                        + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);
                String formattime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":"
                        + Util.add0(today.get(Calendar.MINUTE), 2) + ":" + Util.add0(today.get(Calendar.SECOND), 2);

                this.maincategory = Util.getIntValue(fu.getParameter("maincategory"), 0);
                this.subcategory = Util.getIntValue(fu.getParameter("subcategory"), 0);
                this.seccategory = Util.getIntValue(fu.getParameter("seccategory"), 0);
                this.doclangurage = Util.getIntValue(fu.getParameter("doclangurage"), 7);
                this.docapprovable = fu.getParameter("docapprovable");
                this.docreplyable = fu.getParameter("docreplyable");
                this.isreply = Util.null2String(fu.getParameter("isreply"));
                this.replydocid = Util.getIntValue(fu.getParameter("replydocid"), 0);
                this.docsubject = fu.getParameter("docsubject");
                this.docsubject = interceptString(this.docsubject,400);
                this.docpublishtype = "0";

                this.itemid = Util.getIntValue(fu.getParameter("itemid"), 0);
                this.itemmaincategoryid = Util.getIntValue(fu.getParameter("itemmaincategoryid"), 0);
                this.hrmresid = Util.getIntValue(fu.getParameter("hrmresid"), 0);
                this.assetid = Util.getIntValue(fu.getParameter("assetid"), 0);
                this.crmid = Util.getIntValue(fu.getParameter("crmid"), 0);
                this.projectid = Util.getIntValue(fu.getParameter("projectid"), 0);
                this.financeid = Util.getIntValue(fu.getParameter("financeid"), 0);
                this.doccreaterid = createrid;
                this.ownerid = this.doccreaterid;

                ResourceComInfo rc = new ResourceComInfo();
                this.docdepartmentid = Util.getIntValue(rc.getDepartmentID("createrid"), 0);
                this.doccreatedate = formatdate;
                this.doccreatetime = formattime;
                this.doclastmoduserid = this.doccreaterid;
                this.doclastmoddate = formatdate;
                this.doclastmodtime = formattime;
                this.docapproveuserid = 0;
                this.docapprovedate = "";
                this.docapprovetime = "";
                this.docarchiveuserid = 0;
                this.docarchivedate = "";
                this.docarchivetime = "";

                String tmpstatus = "0";
                if (tmpstatus.equals("1") && docapprovable.equals("1") && !isreply.equals("1")) { // 是保存的非回复文档,要审批，还没有审批的(isreply可能为空），置为需审批状态
                    tmpstatus = "3";
                }
                if (tmpstatus.equals("1") && isreply.equals("1")) { // 是保存的回复文档的（是不要审批，直接置成１）
                    tmpstatus = "1";
                }
                this.docstatus = tmpstatus;

                if (Util.null2String(fu.getParameter("parentids")).equals("")) {
                    this.parentids = this.id + "";
                } else
                    this.parentids = Util.null2String(fu.getParameter("parentids")) + "," + this.id;

                this.keyword = Util.null2String(fu.getParameter("keyword"));
                /* 文档的关键字 */

                int docid = this.id;

                this.accessorycount = accessorynumtrue;

                if (isreply.equals("1")) {
                    AddReplayDocCount(rsSql); // 修改回复记录条数
                }

                this.replaydoccount = 0; /* 回复文档总数 */
                this.usertype = Util.null2String(fu.getParameter("usertype"));
                /* 创建的用户类型 1: 内部 2: 外部 */
                this.topage = Util.null2String(fu.getParameter("topage"));

                this.contractman = Util.null2String(fu.getParameter("contractman"));
                this.contractstartdate = Util.null2String(fu.getParameter("contractstartdate"));
                this.contractenddate = Util.null2String(fu.getParameter("contractenddate"));
                this.docmodule = Util.null2String(fu.getParameter("docmodule"));
                this.proenddate = Util.null2String(fu.getParameter("proenddate"));
                this.typeid = Util.getIntValue(fu.getParameter("typeid"), 0);
                this.urlfrom = Util.null2String(fu.getParameter("urlfrom"));
                this.orderable = "" + scc.getSecOrderable(this.seccategory);
                AddDocInfo();
                AddShareInfo();
            }
        } catch (Exception e) {
            writeLog(e);
            return opera + "_1";
        }

        return opera;

    }

    /**
     * 存储文档内容
     * 
     * @param userName 用户ID
     * @param passwd 用户密码
     * @param docSubject 文档主题
     * @param mainCatory 主目录ID
     * @param secCatory 分目录ID
     * @param subCatory 子目录ID
     * @param content 文档内容
     * @param filenames 上传附件文本框的名称
     * @param req HttpServletRequest 对象
     * @param res HttpServletResponse 对象
     * @param fu FileUpload对象存储了文档地所有信息
     * @param creatid 创建者ID
     * @param docStatus 文档状态
     * @return 文档的操作类型
     * @throws Exception
     */
    public String UploadDoc(String userName, String passwd, String docSubject, String mainCatory, String secCatory,
            String subCatory, String content, String filenames, HttpServletRequest req, HttpServletResponse res,
            FileUpload fu, int creatid, String docStatus) throws Exception {

        String opera = "";
        String docmain = "";
        RecordSet rsSql = new RecordSet();
        // System.out.println("creatid is " +creatid) ;

        try {
            opera = "addsave";

            if (opera.equals("addsave") || opera.equals("adddraft")) {

                this.id = getNextDocId(rsSql);

                int accessorynum = 1;
                String fileids;
                fileids = "0";

                int accessorynumtrue = 0;

                for (int i = 0; i < accessorynum; i++) {
                    if (Util.getIntValue(fileids, 0) == 0)
                        continue;
                    accessorynumtrue++;
                    imgManger.resetParameter();
                    imgManger.setDocid(this.id);
                    imgManger.setImagefileid(Util.getIntValue(fileids, 0));
                    imgManger.setImagefilename(filenames);
                    imgManger.setDocfiletype("2");
                    imgManger.setIsextfile("1");
                    imgManger.AddDocImageInfo();
                }

                this.doccontent = Util.toScreen(content, 7, "0");
                // System.out.println("newcontent is " +doccontent) ;

                Calendar today = Calendar.getInstance();
                String formatdate = Util.add0(today.get(Calendar.YEAR), 4) + "-"
                        + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-"
                        + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);
                String formattime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":"
                        + Util.add0(today.get(Calendar.MINUTE), 2) + ":" + Util.add0(today.get(Calendar.SECOND), 2);

                this.maincategory = Util.getIntValue(mainCatory, 0);
                this.subcategory = Util.getIntValue(secCatory, 0);
                this.seccategory = Util.getIntValue(subCatory, 0);
                this.doclangurage = 7;
                this.docapprovable = " ";
                this.docreplyable = " ";
                this.isreply = Util.null2String(fu.getParameter("isreply"));
                this.replydocid = Util.getIntValue(fu.getParameter("replydocid"), 0);
                this.docsubject = docSubject;
                this.docsubject = interceptString(this.docsubject,400);                
                // System.out.println("docsubject is :" + docsubject) ;

                this.docpublishtype = "0";

                this.itemid = Util.getIntValue(fu.getParameter("itemid"), 0);
                this.itemmaincategoryid = Util.getIntValue(fu.getParameter("itemmaincategoryid"), 0);
                this.hrmresid = Util.getIntValue(fu.getParameter("hrmresid"), 0);
                this.assetid = Util.getIntValue(fu.getParameter("assetid"), 0);
                this.crmid = Util.getIntValue(fu.getParameter("crmid"), 0);
                this.projectid = Util.getIntValue(fu.getParameter("projectid"), 0);
                this.financeid = Util.getIntValue(fu.getParameter("financeid"), 0);
                this.doccreaterid = creatid;
                this.ownerid = this.doccreaterid;

                ResourceComInfo rc = new ResourceComInfo();
                this.docdepartmentid = Util.getIntValue(rc.getDepartmentID("" + creatid), 0);
                // System.out.println(docdepartmentid) ;
                this.doccreatedate = formatdate;
                this.doccreatetime = formattime;
                this.doclastmoduserid = this.doccreaterid;
                this.doclastmoddate = formatdate;
                this.doclastmodtime = formattime;
                this.docapproveuserid = 0;
                this.docapprovedate = "";
                this.docapprovetime = "";
                this.docarchiveuserid = 0;
                this.docarchivedate = "";
                this.docarchivetime = "";

                /*
                 * String tmpstatus = "0" ; if(tmpstatus.equals("1") && docapprovable.equals("1") &&
                 * !isreply.equals("1"))//是保存的非回复文档,要审批，还没有审批的(isreply可能为空），置为需审批状态 {tmpstatus="3";}
                 * if(tmpstatus.equals("1") && isreply.equals("1"))//是保存的回复文档的（是不要审批，直接置成１） {tmpstatus="1";}
                 */
                this.docstatus = docStatus;

                if (Util.null2String(fu.getParameter("parentids")).equals("")) {
                    this.parentids = this.id + "";
                } else
                    this.parentids = Util.null2String(fu.getParameter("parentids")) + "," + this.id;

                this.keyword = Util.null2String(fu.getParameter("keyword"));
                /* 文档的关键字 */

                int docid = this.id;

                this.accessorycount = accessorynumtrue;

                if (isreply.equals("1")) {
                    AddReplayDocCount(rsSql); // 修改回复记录条数
                }

                this.replaydoccount = 0; /* 回复文档总数 */
                this.usertype = "1"; /* 创建的用户类型 1: 内部 2: 外部 */
                this.topage = Util.null2String(fu.getParameter("topage"));

                this.contractman = Util.null2String(fu.getParameter("contractman"));
                this.contractstartdate = Util.null2String(fu.getParameter("contractstartdate"));
                this.contractenddate = Util.null2String(fu.getParameter("contractenddate"));
                this.docmodule = Util.null2String(fu.getParameter("docmodule"));
                this.proenddate = Util.null2String(fu.getParameter("proenddate"));
                this.typeid = Util.getIntValue(fu.getParameter("typeid"), 0);
                this.urlfrom = Util.null2String(fu.getParameter("urlfrom"));
                this.orderable = "" + scc.getSecOrderable(this.seccategory);
                AddDocInfo();
                AddShareInfo();
            }
        } catch (Exception e) {
            writeLog(e);
            return opera + "_1";
        }

        return opera;
        // System.out.println("doccontent is :" + doccontent) ;

    }

    /**
     * 上传文档到一个文件
     * 
     * @param userName 用户ID
     * @param passwd 用户密码
     * @param docSubject 文档主题
     * @param mainCatory 主目录ID
     * @param secCatory 分目录ID
     * @param subCatory 子目录ID
     * @param content 文档内容
     * @param filenames 上传附件文本框的名称
     * @param req HttpServletRequest 对象
     * @param res HttpServletResponse 对象
     * @param fu FileUpload对象存储了文档地所有信息
     * @param creatid 创建者ID
     * @param docStatus 文档状态
     * @param isNeedReturnDocid 是否需要返回文档ID
     * @param note 文档的备注信息
     * @return 文档的操作类型
     * @throws Exception
     */
    public String UploadDocToFile(String userName, String passwd, String docSubject, String mainCatory,
            String subCatory, String secCatory, String content, String filenames, HttpServletRequest req,
            HttpServletResponse res, FileUpload fu, int createrid, String docStatus, boolean isNeedReturnDocid,
            String note) throws Exception {

        String opera = "";
        String docmain = "";
        RecordSet rsSql = new RecordSet();

        try {
            opera = "addsave";

            if (opera.equals("addsave") || opera.equals("adddraft")) {

                this.id = getNextDocId(rsSql);

                //writeLog(" doc id is " + id);

                int accessorynum = 1;

                String fileids;
                fileids = fu.uploadFiles("accessory1");
                filenames = fu.getFileName();

                //writeLog(" fileids  is " + fileids);
                //writeLog(" filenames  is " + filenames);

                int accessorynumtrue = 0;

                for (int i = 0; i < accessorynum; i++) {
                    if (Util.getIntValue(fileids, 0) == 0)
                        continue;
                    accessorynumtrue++;
                    imgManger.resetParameter();
                    imgManger.setDocid(this.id);
                    imgManger.setImagefileid(Util.getIntValue(fileids, 0));
                    imgManger.setImagefilename(filenames);
                    imgManger.setDocfiletype("2");
                    imgManger.setIsextfile("1");
                    imgManger.AddDocImageInfo();
                }

                this.doccontent = Util.fromBaseEncoding(fu.getParameter("doccontent"), languageid);
                this.doccontent =Util.htmlFilter4UTF8(this.doccontent );
                
                Calendar today = Calendar.getInstance();
                String formatdate = Util.add0(today.get(Calendar.YEAR), 4) + "-"
                        + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-"
                        + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);
                String formattime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":"
                        + Util.add0(today.get(Calendar.MINUTE), 2) + ":" + Util.add0(today.get(Calendar.SECOND), 2);

                this.maincategory = Util.getIntValue(mainCatory);
                this.subcategory = Util.getIntValue(subCatory);
                this.seccategory = Util.getIntValue(secCatory);
                this.doclangurage = 7;
                this.docapprovable = "0";
                this.docreplyable = fu.getParameter("docreplyable");
                this.isreply = Util.null2String(fu.getParameter("isreply"));
                this.replydocid = Util.getIntValue(fu.getParameter("replydocid"), 0);
                this.docsubject = docSubject;
                this.docsubject = interceptString(this.docsubject,400);
                
                this.docpublishtype = "0";

                this.itemid = Util.getIntValue(fu.getParameter("itemid"), 0);
                this.itemmaincategoryid = Util.getIntValue(fu.getParameter("itemmaincategoryid"), 0);
                this.hrmresid = Util.getIntValue(fu.getParameter("hrmresid"), 0);
                this.assetid = Util.getIntValue(fu.getParameter("assetid"), 0);
                this.crmid = Util.getIntValue(fu.getParameter("crmid"), 0);
                this.projectid = Util.getIntValue(fu.getParameter("projectid"), 0);
                this.financeid = Util.getIntValue(fu.getParameter("financeid"), 0);
                this.doccreaterid = createrid;
                this.ownerid = this.doccreaterid;

                ResourceComInfo rc = new ResourceComInfo();
                this.docdepartmentid = Util.getIntValue(rc.getDepartmentID("" + createrid), 0);
                this.doccreatedate = formatdate;
                this.doccreatetime = formattime;
                this.doclastmoduserid = this.doccreaterid;
                this.doclastmoddate = formatdate;
                this.doclastmodtime = formattime;
                this.docapproveuserid = 0;
                this.docapprovedate = "";
                this.docapprovetime = "";
                this.docarchiveuserid = 0;
                this.docarchivedate = "";
                this.docarchivetime = "";

                String tmpstatus = "0";
                if (tmpstatus.equals("1") && docapprovable.equals("1") && !isreply.equals("1")) { // 是保存的非回复文档,要审批，还没有审批的(isreply可能为空），置为需审批状态
                    tmpstatus = "3";
                }
                if (tmpstatus.equals("1") && isreply.equals("1")) { // 是保存的回复文档的（是不要审批，直接置成１）
                    tmpstatus = "1";
                }
                this.docstatus = docStatus;

                if (Util.null2String(fu.getParameter("parentids")).equals("")) {
                    this.parentids = this.id + "";
                } else
                    this.parentids = Util.null2String(fu.getParameter("parentids")) + "," + this.id;

                this.keyword = Util.null2String(fu.getParameter("keyword"));
                /* 文档的关键字 */

                /*
                 * if (isNeedReturnDocid) { return ""+docid ; }
                 */

                this.accessorycount = accessorynumtrue;

                if (isreply.equals("1")) {
                    AddReplayDocCount(rsSql); // 修改回复记录条数
                }

                this.replaydoccount = 0; /* 回复文档总数 */
                this.usertype = "1"; /* 创建的用户类型 1: 内部 2: 外部 */
                this.topage = Util.null2String(fu.getParameter("topage"));

                this.contractman = Util.null2String(fu.getParameter("contractman"));
                this.contractstartdate = Util.null2String(fu.getParameter("contractstartdate"));
                this.contractenddate = Util.null2String(fu.getParameter("contractenddate"));
                this.docmodule = Util.null2String(fu.getParameter("docmodule"));
                this.proenddate = Util.null2String(fu.getParameter("proenddate"));
                this.typeid = Util.getIntValue(fu.getParameter("typeid"), 0);
                this.urlfrom = Util.null2String(fu.getParameter("urlfrom"));
                this.orderable = "" + scc.getSecOrderable(this.seccategory);
                AddDocInfo();
                AddShareInfo();

            }
        } catch (Exception e) {
            writeLog(e);
            return "";
        }

        return "" + id;

    }

    /**
     * 上传文档到一个文件
     * 
     * @param userName 用户ID
     * @param passwd 用户密码
     * @param docSubject 文档主题
     * @param mainCatory 主目录ID
     * @param secCatory 分目录ID
     * @param subCatory 子目录ID
     * @param content 文档内容
     * @param filenames 上传附件文本框的名称
     * @param req HttpServletRequest 对象
     * @param res HttpServletResponse 对象
     * @param fu FileUpload对象存储了文档地所有信息
     * @param creatid 创建者ID
     * @param docStatus 文档状态
     * @param isNeedReturnDocid 是否需要返回文档ID
     * @param note 文档的备注信息
     * @return 文档的操作类型
     * @throws Exception
     */
    public String UploadDocToContent(String userName, String passwd, String docSubject, String mainCatory,
            String subCatory, String secCatory, String content, String filenames, HttpServletRequest req,
            HttpServletResponse res, FileUpload fu, int creatid, String docStatus, String note) throws Exception {

        String opera = "";
        String docmain = "";
        RecordSet rsSql = new RecordSet();
        // System.out.println("creatid is " +creatid) ;

        try {
            opera = "addsave";

            if (opera.equals("addsave") || opera.equals("adddraft")) {

                this.id = getNextDocId(rsSql);

                //writeLog(" doc id is " + id);

                int accessorynum = 1;
                String fileids;
                fileids = "0";


                int accessorynumtrue = 0;

                for (int i = 0; i < accessorynum; i++) {
                    if (Util.getIntValue(fileids, 0) == 0)
                        continue;
                    accessorynumtrue++;
                    imgManger.resetParameter();
                    imgManger.setDocid(this.id);
                    imgManger.setImagefileid(Util.getIntValue(fileids, 0));
                    imgManger.setImagefilename(filenames);
                    imgManger.setDocfiletype("2");
                    imgManger.setIsextfile("1");
                    imgManger.AddDocImageInfo();
                }

                this.doccontent = Util.toScreen(content, 7, "0");
                // System.out.println("newcontent is " +doccontent) ;

                Calendar today = Calendar.getInstance();
                String formatdate = Util.add0(today.get(Calendar.YEAR), 4) + "-"
                        + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-"
                        + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);
                String formattime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":"
                        + Util.add0(today.get(Calendar.MINUTE), 2) + ":" + Util.add0(today.get(Calendar.SECOND), 2);

                this.maincategory = Util.getIntValue(mainCatory, 0);
                this.subcategory = Util.getIntValue(secCatory, 0);
                this.seccategory = Util.getIntValue(subCatory, 0);
                this.doclangurage = 7;
                this.docapprovable = " ";
                this.docreplyable = " ";
                this.isreply = Util.null2String(fu.getParameter("isreply"));
                this.replydocid = Util.getIntValue(fu.getParameter("replydocid"), 0);
                this.docsubject = docSubject;
                this.docsubject = interceptString(this.docsubject,400);                
                // System.out.println("docsubject is :" + docsubject) ;

                this.docpublishtype = "0";

                this.itemid = Util.getIntValue(fu.getParameter("itemid"), 0);
                this.itemmaincategoryid = Util.getIntValue(fu.getParameter("itemmaincategoryid"), 0);
                this.hrmresid = Util.getIntValue(fu.getParameter("hrmresid"), 0);
                this.assetid = Util.getIntValue(fu.getParameter("assetid"), 0);
                this.crmid = Util.getIntValue(fu.getParameter("crmid"), 0);
                this.projectid = Util.getIntValue(fu.getParameter("projectid"), 0);
                this.financeid = Util.getIntValue(fu.getParameter("financeid"), 0);
                this.doccreaterid = creatid;
                this.ownerid = this.doccreaterid;

                ResourceComInfo rc = new ResourceComInfo();
                this.docdepartmentid = Util.getIntValue(rc.getDepartmentID("" + creatid), 0);
                // System.out.println(docdepartmentid) ;
                this.doccreatedate = formatdate;
                this.doccreatetime = formattime;
                this.doclastmoduserid = this.doccreaterid;
                this.doclastmoddate = formatdate;
                this.doclastmodtime = formattime;
                this.docapproveuserid = 0;
                this.docapprovedate = "";
                this.docapprovetime = "";
                this.docarchiveuserid = 0;
                this.docarchivedate = "";
                this.docarchivetime = "";

                /*
                 * String tmpstatus = "0" ; if(tmpstatus.equals("1") && docapprovable.equals("1") &&
                 * !isreply.equals("1"))//是保存的非回复文档,要审批，还没有审批的(isreply可能为空），置为需审批状态 {tmpstatus="3";}
                 * if(tmpstatus.equals("1") && isreply.equals("1"))//是保存的回复文档的（是不要审批，直接置成１） {tmpstatus="1";}
                 */
                this.docstatus = docStatus;

                if (Util.null2String(fu.getParameter("parentids")).equals("")) {
                    this.parentids = this.id + "";
                } else
                    this.parentids = Util.null2String(fu.getParameter("parentids")) + "," + this.id;

                this.keyword = Util.null2String(fu.getParameter("keyword"));
                /* 文档的关键字 */

                int docid = this.id;

                this.accessorycount = accessorynumtrue;

                if (isreply.equals("1")) {
                    AddReplayDocCount(rsSql); // 修改回复记录条数
                }

                this.replaydoccount = 0; /* 回复文档总数 */
                this.usertype = "1"; /* 创建的用户类型 1: 内部 2: 外部 */
                this.topage = Util.null2String(fu.getParameter("topage"));

                this.contractman = Util.null2String(fu.getParameter("contractman"));
                this.contractstartdate = Util.null2String(fu.getParameter("contractstartdate"));
                this.contractenddate = Util.null2String(fu.getParameter("contractenddate"));
                this.docmodule = Util.null2String(fu.getParameter("docmodule"));
                this.proenddate = Util.null2String(fu.getParameter("proenddate"));
                this.typeid = Util.getIntValue(fu.getParameter("typeid"), 0);
                this.urlfrom = Util.null2String(fu.getParameter("urlfrom"));
                this.orderable = "" + scc.getSecOrderable(this.seccategory);
                AddDocInfo();
                AddShareInfo();
            }
        } catch (Exception e) {
            writeLog(e);
            return " ";
        }

        return "" + id;
        // System.out.println("doccontent is :" + doccontent) ;

    }

    /**
     * 上传文档到一个文件2
     * 
     * @param userName 用户ID
     * @param passwd 用户密码
     * @param docSubject 文档主题
     * @param mainCatory 主目录ID
     * @param secCatory 分目录ID
     * @param subCatory 子目录ID
     * @param content 文档内容
     * @param filenames 上传附件文本框的名称
     * @param req HttpServletRequest 对象
     * @param res HttpServletResponse 对象
     * @param fu FileUpload对象存储了文档地所有信息
     * @param creatid 创建者ID
     * @param docStatus 文档状态
     * @param isNeedReturnDocid 是否需要返回文档ID
     * @param note 文档的备注信息
     */
    public void UploadDocToFile2(String userName, String passwd, String docSubject, String mainCatory,
            String subCatory, String secCatory, String content, String filenames, HttpServletRequest req,
            HttpServletResponse res, FileUpload fu, int creatid, String docStatus, String docid, String note) {
        String docid_new = "";
        String content_new = " ";
        boolean isNeedReturnDocid = true;
        try {
            docid_new = UploadDocToFile(userName, passwd, docSubject, mainCatory, subCatory, secCatory, content,
                    filenames, req, res, fu, creatid, docStatus, isNeedReturnDocid, note);
        } catch (Exception e) {
            //System.out.println(e.getMessage());
			writeLog(e);
        }
        RecordSet rsSql = new RecordSet();
        String sql_updateImagefile = "update docimagefile set docid = " + docid + " where docid =" + docid_new;
        String sql_deldocdetail = "delete docdetail where id = " + docid_new;
        String sql_updatedocdetail = "update docdetail set accessorycount = 1 where id =" + docid;

        rsSql.executeSql(sql_updateImagefile);
        rsSql.executeSql(sql_deldocdetail);
        rsSql.executeSql(sql_updatedocdetail);

        // System.out.println("sql_updateImagefile is : "+sql_updateImagefile) ;
        // System.out.println("sql_deldocdetail is : "+sql_deldocdetail) ;
        // System.out.println("sql_updatedocdetail is : "+sql_updatedocdetail) ;

    }

    /**
     * 文档移动
     * 
     * @throws Exception
     */
    public void moveDoc() throws Exception {
    	int oldsecid = dc.getDocSecCategory(id+"");
    	
        String sql = "update DocDetail set maincategory=?,subcategory=?,seccategory=? where id = " + id;
        String sqlDummy = "update DocDummyDetail set docid =? where docid="+id;
        String sqllog = "update DocDetail set maincategory=" + maincategory + ",subcategory=" + subcategory
                + ",seccategory=" + seccategory + " where id = " + id;
        String sqlShareinnerdoc = " update shareinnerdoc set sec_category = "+seccategory +" where sourceid = "+id;
        new RecordSet().executeUpdate(sqlShareinnerdoc);
        RecordSet statement = new RecordSet();
        try {
            statement.executeUpdate(sql,maincategory,subcategory,seccategory);
            
            statement.executeUpdate(sqlDummy,id);
            
            if(customDataIdMapping==null || customDataIdMapping.length == 0) {
                RecordSet rsSql = new RecordSet();
                rsSql.executeSql("update cus_fielddata set  scopeId="+this.seccategory+" where   scope='DocCustomFieldBySecCategory'  and id="+this.id);            
                int tempDocEditionId=-1;
                rsSql.executeSql("select docEditionId from DocDetail where id="+this.id);
                if(rsSql.next()){
                	tempDocEditionId=Util.getIntValue(rsSql.getString("docEditionId"));
                }
                if(tempDocEditionId>0){
                    rsSql.executeSql("update cus_fielddata set  scopeId="+this.seccategory+" where   scope='DocCustomFieldBySecCategory'  and exists (select 1 from DocDetail where id=cus_fielddata.id  and docEditionId="+tempDocEditionId+")");
					rsSql.executeSql("update docdetail set seccategory=" + this.seccategory+" where docEditionId="+tempDocEditionId);
                }
            } else {
            	String srcNameStr = "";
            	List srcNameList=new ArrayList();
            	int srcFieldId=-1;
            	String srcFieldValue=null;
            	String srcFieldShowName=null;
                String cusFieldDataSrcSql=null;
                String cusFieldDataSrcStr="";
                
            	String objNameStr = "";
            	List objNameList=new ArrayList();
            	int objFieldId=-1;
            	String objFieldValue=null;            	
                String cusFieldDataObjSql=null;
                String cusFieldDataObjStr="";
                
            	Map objNameSrcNameMap=new HashMap();
            	Map srcFieldValueAndFieldShowNameMap=null;
            	
				RecordSet rsCus=new RecordSet();
				//customDataIdMapping = removedouble(customDataIdMapping);
            	for(int i=0;i<customDataIdMapping.length;i++){
            		List ids = Util.TokenizerString(customDataIdMapping[i], "_");					
					rsCus.execute("select fieldname from cus_formdict where id="+ids.get(0));
					if(rsCus.next()){
						srcNameStr += ","+rsCus.getString("fieldname");
					}
					rsCus.execute("select fieldname from cus_formdict where id="+ids.get(1));
					if(rsCus.next()){
						objNameStr += ","+rsCus.getString("fieldname");
					}
            		//srcNameStr += ",field" + ids.get(0);
            		//objNameStr += ",field" + ids.get(1);
            		objNameSrcNameMap.put(""+ids.get(1),""+ids.get(0));
            		srcNameList.add(""+ids.get(0));
            		objNameList.add(""+ids.get(1));            		
            	}
            	srcNameStr = srcNameStr.substring(1);
            	objNameStr = objNameStr.substring(1);
            	
            	RecordSet rsSql = new RecordSet();
            	RecordSet rsTemp=new RecordSet();
            	
            	List seqorderList =new ArrayList();
            	int seqorder = -1;
            	String fieldDbType=null;
            	String fieldHtmlType=null;
				String fieldName=null;
                int fieldLength=0;            	
            	Map fieldHtmlTypeMap=new HashMap();
            	
            	int tempDocEditionId=-1;
            	rsSql.executeSql("select docEditionId from DocDetail where id="+this.id);
                if(rsSql.next()){
                	tempDocEditionId=Util.getIntValue(rsSql.getString("docEditionId"));
                }
                if(tempDocEditionId>0){
					rsSql.executeSql("update docdetail set seccategory=" + this.seccategory+" where docEditionId="+tempDocEditionId);
                	sql = "select * from cus_fielddata where scope='DocCustomFieldBySecCategory' and scopeid=" + oldsecid + " and exists (select 1 from DocDetail where id=cus_fielddata.id  and docEditionId="+tempDocEditionId+")";
                }else{
                	sql = "select * from cus_fielddata where scope='DocCustomFieldBySecCategory' and scopeid=" + oldsecid + " and id="+this.id;
                }
                rsSql.executeSql(sql);
            	while(rsSql.next()){
	            	seqorder = Util.getIntValue(rsSql.getString("seqorder"),-1);
	            	if(seqorder>0){
		            	seqorderList.add(""+seqorder);
	            	}
            	}
	            	
            	Map cusFormDictDataMap=new HashMap();	            	
			    rsSql.executeSql("select id,fieldDbType,fieldHtmlType,type,fieldname from cus_formdict");
	            while(rsSql.next()){
	            	cusFormDictDataMap.put("fieldDbType"+Util.null2String(rsSql.getString("id")),Util.null2String(rsSql.getString("fieldDbType")));
	            	cusFormDictDataMap.put("fieldHtmlType"+Util.null2String(rsSql.getString("id")),Util.null2String(rsSql.getString("fieldHtmlType")));
	            	cusFormDictDataMap.put("type"+Util.null2String(rsSql.getString("id")),Util.null2String(rsSql.getString("type")));	            	
					cusFormDictDataMap.put("fieldName"+Util.null2String(rsSql.getString("id")),Util.null2String(rsSql.getString("fieldname")));	            	

	            }
	            	
	            for(int seqorderIndex=0;seqorderIndex<seqorderList.size();seqorderIndex++){
	            	seqorder=Util.getIntValue((String)seqorderList.get(seqorderIndex),-1);
	            	srcFieldValueAndFieldShowNameMap=new HashMap();
	            	cusFieldDataSrcSql="update cus_fielddata set ";
	            	cusFieldDataObjSql="update cus_fielddata set scopeId="+this.seccategory+",";
	            	cusFieldDataSrcStr="";
	            	cusFieldDataObjStr="";
	            		
	            	rsSql.executeSql("select "+srcNameStr+" from cus_fielddata where seqorder= "+seqorder);
	            	if(rsSql.next()){
	            		for(int i=0;i<srcNameList.size();i++){
	            			srcFieldId=Util.getIntValue((String)srcNameList.get(i),-1);
	            			srcFieldValue=Util.null2String(rsSql.getString(i+1));
	            			srcFieldShowName="";
	            			fieldDbType=Util.null2String((String)cusFormDictDataMap.get("fieldDbType"+srcFieldId));	            			
	            			fieldHtmlType=Util.null2String((String)cusFormDictDataMap.get("fieldHtmlType"+srcFieldId));
	            			fieldName=Util.null2String((String)cusFormDictDataMap.get("fieldName"+srcFieldId));
							if(fieldHtmlType.equals("5")){
	                    		rsTemp.executeSql("  select selectName from cus_selectitem where fieldId="+srcFieldId+" and selectValue="+srcFieldValue);
	                    		if(rsTemp.next()){
	                    			srcFieldShowName=Util.null2String(rsTemp.getString("selectName"));
	                    			srcFieldValueAndFieldShowNameMap.put("srcFieldShowName"+srcFieldId,srcFieldShowName);           			
	                    		}	            				
	            			}
                			srcFieldValueAndFieldShowNameMap.put("srcFieldValue"+srcFieldId,srcFieldValue);
                			
                			if(cusFieldDataSrcStr.indexOf("," + fieldName + "=")<0){
                    			cusFieldDataSrcStr += "," + fieldName + "=";
                                if (fieldDbType.startsWith("text") || fieldDbType.startsWith("char")|| fieldDbType.startsWith("varchar")|| fieldDbType.startsWith("browser")) {
                                	cusFieldDataSrcStr += "''";
                                } else {
                                	cusFieldDataSrcStr += -1;
                                }                 				
                			}                			
               			
	            		}
		            }
	            	
	            	for(int i=0;i<objNameList.size();i++){
            			objFieldId=Util.getIntValue((String)objNameList.get(i),-1);
            			srcFieldId=Util.getIntValue((String)objNameSrcNameMap.get(""+objFieldId));
            			srcFieldShowName=Util.null2String((String)srcFieldValueAndFieldShowNameMap.get("srcFieldShowName"+srcFieldId));           			
            			objFieldValue=Util.null2String((String)srcFieldValueAndFieldShowNameMap.get("srcFieldValue"+srcFieldId));

            			fieldDbType=Util.null2String((String)cusFormDictDataMap.get("fieldDbType"+objFieldId));	            			
            			fieldHtmlType=Util.null2String((String)cusFormDictDataMap.get("fieldHtmlType"+objFieldId));
            			fieldName=Util.null2String((String)cusFormDictDataMap.get("fieldName"+objFieldId));
            			if(cusFieldDataObjStr.indexOf("," + fieldName + "=")<0){
                			cusFieldDataObjStr += "," + fieldName + "=";
                            if (fieldDbType.startsWith("text") || fieldDbType.startsWith("char")|| fieldDbType.startsWith("varchar")|| fieldDbType.startsWith("browser")) {
                        		if(fieldDbType.indexOf("(")>=0&&fieldDbType.indexOf(")")>fieldDbType.indexOf("(")+1){
                        			fieldLength=Util.getIntValue(fieldDbType.substring(fieldDbType.indexOf("(")+1,fieldDbType.indexOf(")")),0);
                        		}
                        		if(fieldLength>0){
                        			cusFieldDataObjStr += "'" + interceptString(objFieldValue,fieldLength) + "'";
                        		}else{
                        			cusFieldDataObjStr += "'" + objFieldValue + "'";
                        		}
                            } else {
                            	if(fieldHtmlType.equals("5")){
                            		objFieldValue=this.getNewSelectValue(srcFieldShowName,objFieldValue,objFieldId);
                            	}
                            	cusFieldDataObjStr += Util.getIntValue(objFieldValue,-1);
                            }           				
            			}
            			            			
	            	}
		            	
	                if (!cusFieldDataSrcStr.equals("")) {
	                	cusFieldDataSrcStr = cusFieldDataSrcStr.substring(1);
	                    cusFieldDataSrcSql += cusFieldDataSrcStr + " where seqorder= "+seqorder;
	                    rsSql.executeSql(cusFieldDataSrcSql);
	                }
	                
	                if (!cusFieldDataObjStr.equals("")) {
	                	cusFieldDataObjStr = cusFieldDataObjStr.substring(1);
	                    cusFieldDataObjSql += cusFieldDataObjStr + " where seqorder= "+seqorder;
	                    rsSql.executeSql(cusFieldDataObjSql);
	                }	                

		        }                    	
            }
            
            log.resetParameter();
            log.setDocId(this.id);
            log.setDocSubject(this.docsubject);
            log.setOperateType("11");
            log.setOperateUserid(userid);
            log.setUsertype(this.usertype);
            log.setClientAddress(this.clientip);
            log.setDocCreater(this.doccreaterid);
            log.setDocLogInfo();

            dc.updateDocInfoCache("" + id);
        } catch (Exception e) {
            writeLog(e);
            throw e;
        } finally {
        }
    }

    /**
     * 文档复制
     * 
     * @throws Exception
     */
    public int copyDoc() throws Exception {
        RecordSet rs = new RecordSet();
        int oldid = this.id;
        this.id = getNextDocId(rs);
        
       	//copyDocToNewDoc(oldid);		
		copyDocToNewDoc(oldid,true,"",true,true,"'1'",true,true,false);

        log.resetParameter();
        log.setDocId(this.id);
        log.setDocSubject(this.docsubject);
        log.setOperateType("12");
        log.setOperateUserid(userid);
        log.setUsertype(this.usertype);
        log.setClientAddress(this.clientip);
        log.setDocCreater(this.doccreaterid);
        log.setDocLogInfo();
        return this.id;
    }

    /**
     * 文档复制
     * aiyh 新增
     * @throws Exception
     */
    public int copyDoc(boolean copyAttachment) throws Exception {
        RecordSet rs = new RecordSet();
        int oldid = this.id;
        this.id = getNextDocId(rs);

        if(copyAttachment){
            copyDocToNewDoc(oldid,true,"",true,true,"'1'",true,true,false);
        }else{
            copyDocToNewDoc(oldid,true,"",true,true,"",true,false,false);
        }

        log.resetParameter();
        log.setDocId(this.id);
        log.setDocSubject(this.docsubject);
        log.setOperateType("12");
        log.setOperateUserid(userid);
        log.setUsertype(this.usertype);
        log.setClientAddress(this.clientip);
        log.setDocCreater(this.doccreaterid);
        log.setDocLogInfo();
        return this.id;
    }

    /**
     * 文档复制
     *
     * @throws Exception
     */
    public void copyDocNew() throws Exception {
        RecordSet rs = new RecordSet();
        int oldid = this.id;
        this.id = getNextDocId(rs);

        //copyDocToNewDoc(oldid);
        copyDocToNewDoc(oldid,true,"",true,true,"'1'",false,true,true);

        log.resetParameter();
        log.setDocId(this.id);
        log.setDocSubject(this.docsubject);
        log.setOperateType("12");
        log.setOperateUserid(userid);
        log.setUsertype(this.usertype);
        log.setClientAddress(this.clientip);
        log.setDocCreater(this.doccreaterid);
        log.setDocLogInfo();
    }
    /**
     * 文档复制
     * 
     * 触发子流程时专用，
     * 
     * 不复制权限，不改变状态,只复制最新版本的文档
     * 
     * @throws Exception
     */
    public void copyDocForNoRightAndNoChangeStatus() throws Exception {
        RecordSet rs = new RecordSet();
        int oldid = this.id;
        this.id = getNextDocId(rs);
        
        //copyDocToNewDoc(oldid,true,"",true,false,"");
		copyDocToNewDoc(oldid,true,"",true,true,"",true,true,false);
        log.resetParameter();
        log.setDocId(this.id);
        log.setDocSubject(this.docsubject);
        log.setOperateType("12");
        log.setOperateUserid(userid);
        log.setUsertype(this.usertype);
        log.setClientAddress(this.clientip);
        log.setDocCreater(this.doccreaterid);
        log.setDocLogInfo();
    }
    
    
    /**
     * 得到最新文档的ID+1
     * 
     * @param rs RecordSet对象
     * @return 最新文档的ID+1
     * @throws Exception
     */
    public synchronized int getNextDocId(RecordSet rs) throws Exception {
//        int docindex = 0;
//        rs.executeProc("SequenceIndex_SelectNextID", "docid");
//        if (rs.next())
//            docindex = rs.getInt(1);
        
        int docindex=docIdUpdate.getDocNewId();

        return docindex;
    }

    /**
     * 得到最新文档Edition的ID+1
     * 
     * @param rs RecordSet对象
     * @return 最新文档Edition的ID+1
     * @throws Exception
     */
    public synchronized int getNextEditionId(RecordSet rs) throws Exception {
        int docindex = 0;
        rs.executeProc("SequenceIndex_SelectNextID", "doceditionid");
        if (rs.next())
            docindex = rs.getInt(1);

        return docindex;
    }
    
    /**
     * 让文档的回复数自动加1
     * 
     * @param rs RecordSet对象
     * @throws Exception
     */
    public void AddReplayDocCount(RecordSet rs) throws Exception {
        String pare = this.parentids;
        String sql = "update docdetail set replaydoccount=replaydoccount+1 where id in (" + pare + ")";
        rs.executeSql(sql);
    }

    /**
     * 据文档id得其parentids，再据parentids对其前级ＩＤ减１
     * 
     * @throws Exception
     */
    public void DeleteReplayDocCount() throws Exception {
        RecordSet recordersql = new RecordSet();

        int replydoccount = 1;
        String pare = "";
        String maindoc = "";
        int docid = this.id;

        String sql = "select maindoc, parentids from docdetail where id=" + docid;
        recordersql.executeSql(sql);
        if (recordersql.next()) {
            pare = recordersql.getString("parentids");
            maindoc = recordersql.getString("maindoc");
        }
        //TD19610
		if(pare!=null&&!pare.equals("")){
	        //是否是最新版本的删除，老版本删除不对前级ID处理
	        if(("" + docid).equals(maindoc)) {
		        String sql2 = "update docdetail set replaydoccount=replaydoccount-" + replydoccount + " where id in (" + pare
		                + ")" + " and replaydoccount > 0";
		        recordersql.executeSql(sql2);
        	}
        }
    }

    /**
     * 添加文档的共享信息
     * 
     * @throws Exception
     */
    public void AddShareInfo() throws Exception {
        char flag = Util.getSeparator();
        RecordSet recordersql = new RecordSet();
        RecordSet recordsql = new RecordSet();
        String secid = "" + this.seccategory;
        
        AppDetachComInfo adci = new AppDetachComInfo();

            //recorder.executeProc("DocSecCategoryShare_SBySecCate", secid);
			recordersql.executeSql(" select * from DocSecCategoryShare where seccategoryid  = "+secid);
            while (recordersql.next()) {
                String ProcPara = "";

                String docid = "" + this.id;
                String sharetype = Util.null2String(recordersql.getString("sharetype"));
                String seclevel = Util.null2String(recordersql.getString("seclevel"));
                String rolelevel = Util.null2String(recordersql.getString("rolelevel"));
                String sharelevel = Util.null2String(recordersql.getString("sharelevel"));
                String userid = Util.null2String(recordersql.getString("userid"));
                String subcompanyid = Util.null2String(recordersql.getString("subcompanyid"));
                String departmentid = Util.null2String(recordersql.getString("departmentid"));
                String roleid = Util.null2String(recordersql.getString("roleid"));
                String foralluser = Util.null2String(recordersql.getString("foralluser"));
                String crmid = Util.null2String(recordersql.getString("crmid"));
                String orgGroupId = Util.null2String(recordersql.getString("orgGroupId"));

				String operategroup = Util.null2String(recordersql.getString("operategroup"));
				int orgid = Util.getIntValue(recordersql.getString("orgid"),0);
				int seclevelmax = Util.getIntValue(recordersql.getString("seclevelmax"),255);
				int includesub = Util.getIntValue(recordersql.getString("includesub"),0);
				String custype = Util.null2String(recordersql.getString("custype"));
				String allmanagers="0";
				String joblevel=Util.getIntValue(recordersql.getString("joblevel"),0)+"";
				String jobdepartment=Util.getIntValue(recordersql.getString("jobdepartment"),0)+"";
				String jobsubcompany=Util.getIntValue(recordersql.getString("jobsubcompany"),0)+"";
				String jobids=Util.getIntValue(recordersql.getString("jobids"),0)+"";
				if(operategroup.equals("1")){
					userid = "" + this.userid;
					if(!this.docCreaterType.equals("1")){					
					  continue;
					}
				  if(Util.null2String(recordersql.getString("sharetype")).equals("1")){
					  sharetype="80";				  
				  }else if(Util.null2String(recordersql.getString("sharetype")).equals("2")){
					  sharetype="81";						  
				  }else if(Util.null2String(recordersql.getString("sharetype")).equals("3")){
					  sharetype="81";
					  allmanagers="1";
				  }else if(Util.null2String(recordersql.getString("sharetype")).equals("4")){
					  sharetype="84";					 
				  }else if(Util.null2String(recordersql.getString("sharetype")).equals("5")){
					  sharetype="85";					 
				  }else if(Util.null2String(recordersql.getString("sharetype")).equals("6")){
					  sharetype="11";
					  jobids=Util.getIntValue(hrc.getJobTitle(userid),0)+"";
					  jobsubcompany=Util.getIntValue(hrc.getSubCompanyID(userid),0)+"";
					  jobdepartment=Util.getIntValue(this.docdepartmentid+"",0)+"";

					
				  }
				
				}else if(operategroup.equals("2")){

				   userid = "" + this.userid;
				   if(!this.docCreaterType.equals("2")){					
					  continue;
					}
				  if(Util.null2String(recordersql.getString("sharetype")).equals("1")){
					  sharetype="-80";				  
				  }else if(Util.null2String(recordersql.getString("sharetype")).equals("2")){
					  sharetype="-81";						  
				  }
				
				
				}else{
						
				  if(Util.null2String(recordersql.getString("sharetype")).equals("7")){

					  sharetype="9";				  
				  }else if(Util.null2String(recordersql.getString("sharetype")).equals("8")){

					  sharetype="-"+custype;						  
				  }
				
				}
				


                if (sharetype.equals("3") && departmentid.equals("0"))
                    departmentid = "" + docdepartmentid;

                
        		List scopes = adci.getAppDetachScopes(this.userid+"");
            	
                
		                ProcPara = docid;
		                ProcPara += flag + sharetype;
		                ProcPara += flag + seclevel;
		                ProcPara += flag + rolelevel;
		                ProcPara += flag + sharelevel;
		                ProcPara += flag + userid;
		                ProcPara += flag + subcompanyid;
		                ProcPara += flag + departmentid;
		                ProcPara += flag + roleid;
		                ProcPara += flag + foralluser;
		                ProcPara += flag + crmid; // CRMID
		                ProcPara += flag + orgGroupId; // orgGroupId
		
		                //record.executeProc("DocShare_IFromDocSecCategory", ProcPara);
		                /** TD12005  =========文档下载权限 开始=============*/
		                String downloadlevel = String.valueOf(Util.getIntValue(recordersql.getString("downloadlevel"), 0));//TD12005
		                ProcPara += flag + downloadlevel; // 文档下载权限
		                /** TD12005  =========文档下载权限 结束=============*/
		                recordsql.executeProc("DocShare_IFromDocSecCat_G", ProcPara);                
		                recordsql.next();
		                int shareid = recordsql.getInt(1);		             
		               recordsql.executeSql("update docshare set isSecDefaultShare=1,allmanagers='"+allmanagers+"',includesub='"+includesub+"', orgid='"+orgid+"',seclevelmax='"+seclevelmax+"',joblevel='"+joblevel+"',jobdepartment='"+jobdepartment+"',jobsubcompany='"+jobsubcompany+"',jobids='"+jobids+"' where id=" + shareid);
            	
            }
           // setAboutCreaterShare(secid);
      
            // 得到实际回复的文档ID,是指被回复文档,而不是主文档,保留主文档的相关共享
            String realReplyDocId = "";
            if (parentids != null) {
                String tempStrs[] = Util.TokenizerString2(parentids, ",");
                if (tempStrs.length >= 2)
                    realReplyDocId = tempStrs[tempStrs.length - 2];
            }
			if(!realReplyDocId.equals("")){
            recordersql.executeProc("DocShare_SelectByDocId", "" + realReplyDocId);
            // recorder.executeProc("DocShare_SelectByDocId", "" + replydocid);
			
            while (recordersql.next()) {
                String ProcPara = "";
                String docid = "" + this.id;
                String sharetype = Util.null2String(recordersql.getString("sharetype"));
                String seclevel = Util.null2String(recordersql.getString("seclevel"));
                String rolelevel = Util.null2String(recordersql.getString("rolelevel"));
                String sharelevel = Util.null2String(recordersql.getString("sharelevel"));
                String userid = Util.null2String(recordersql.getString("userid"));
                String subcompanyid = Util.null2String(recordersql.getString("subcompanyid"));
                String departmentid = Util.null2String(recordersql.getString("departmentid"));
                String roleid = Util.null2String(recordersql.getString("roleid"));
                String foralluser = Util.null2String(recordersql.getString("foralluser"));
                String crmid = Util.null2String(recordersql.getString("crmid"));
                String orgGroupId = Util.null2String(recordersql.getString("orgGroupId"));

				int orgid = Util.getIntValue(recordersql.getString("orgid"),0);
				int seclevelmax = Util.getIntValue(recordersql.getString("seclevelmax"),255);
				int includesub = Util.getIntValue(recordersql.getString("includesub"),0);
				int allmanagers = Util.getIntValue(recordersql.getString("allmanagers"),0);
				String downloadlevel = Util.null2String(recordersql.getString("downloadlevel"));


                if ("80".equals(sharetype)) { // 本人
                    sharetype = "1";

                    String strtempSql = "select count(id) from docshare where docid='" + docid
                            + "' and  sharetype=1 and userid=" + userid + " and sharelevel=" + sharelevel;
                    recordsql.executeSql(strtempSql);
                    if (recordsql.next()) {
                        if (recordsql.getInt(1) > 0)
                            continue;
                    }
                } else if ("81".equals(sharetype)) { // 上级
					 sharetype = "1";
					if(orgid==0){
                    if(allmanagers==0){
                    userid = hrc.getManagerID(userid);
                    
                    if(Util.getIntValue(userid,-1)<=0){
                    	continue;
                    }

                    String strtempSql = "select count(id) from docshare where docid=" + docid
                            + " and  sharetype=1 and userid=" + userid + " and sharelevel=" + sharelevel+"  and allmanagers=0";
                    recordsql.executeSql(strtempSql);
                    if (recordsql.next()) {
                        if (recordsql.getInt(1) > 0)
                            continue;
                    }
					}else if(allmanagers==1){
                      String managerids= hrc.getManagersIDs(""+userid);
					  if(managerids.equals("")){
					            continue;
					      }
					  String[] shareids = Util.TokenizerString2(managerids, ",");
	                  for(int i=0;i<shareids.length;i++){

						   String strtempSql = "select count(id) from docshare where docid=" + docid
                            + " and  sharetype=1 and userid=" + shareids[i] + " and sharelevel=" + sharelevel+"  and allmanagers=0";
                    recordsql.executeSql(strtempSql);
                    if (recordsql.next()) {
                        if (recordsql.getInt(1) > 0)
                            continue;
                    }


					ProcPara = docid;
                    ProcPara += flag + sharetype;
                    ProcPara += flag + seclevel;
                    ProcPara += flag + rolelevel;
                    ProcPara += flag + sharelevel;
                    ProcPara += flag + shareids[i];
                    ProcPara += flag + subcompanyid;
                    ProcPara += flag + departmentid;
                    ProcPara += flag + roleid;
                    ProcPara += flag + foralluser;
                    ProcPara += flag + crmid; // CRMID
                    ProcPara += flag + orgGroupId; // orgGroupId

                    //record.executeProc("DocShare_IFromDocSecCategory", ProcPara);
                    /** TD12005  =========文档下载权限 开始=============*/
                     downloadlevel = String.valueOf(Util.getIntValue(recordersql.getString("downloadlevel"), 0));//TD12005
                    ProcPara += flag + downloadlevel; // 文档下载权限
                    /** TD12005  =========文档下载权限 结束=============*/
                    recordsql.executeProc("DocShare_IFromDocSecCat_G", ProcPara);               
                    recordsql.next();
                    int shareid = recordsql.getInt(1);
                     recordsql.executeSql("update docshare set isSecDefaultShare=1,allmanagers=0,includesub='"+includesub+"', orgid=0,seclevelmax='"+seclevelmax+"' where id=" + shareid);
                	
					  
					  }
                    
					continue;
					
					}
					}else if(orgid<0){
					 recordsql.executeSql("select * from HrmResourceVirtual where virtualtype= "+orgid+" and resourceid="+userid);
                     String managerids2="";
					 if(recordsql.next()){
					   userid = recordsql.getString("managerid");
					   managerids2=recordsql.getString("managerstr");
					 }
					

						 if(allmanagers==0){
							 if(userid.equals("")){
					            continue;
					          }
							 String strtempSql = "select count(id) from docshare where docid=" + docid
                            + " and  sharetype=1 and userid=" + userid + " and sharelevel=" + sharelevel+"  and allmanagers=0";
                    recordsql.executeSql(strtempSql);
                    if (recordsql.next()) {
                        if (recordsql.getInt(1) > 0)
                            continue;
                    }
						 
						 
					 }else if(allmanagers==1){
						    if(managerids2.equals("")){
					            continue;
					          }

					String[] shareids = Util.TokenizerString2(managerids2, ",");
	                  for(int i=0;i<shareids.length;i++){

						   String strtempSql = "select count(id) from docshare where docid=" + docid
                            + " and  sharetype=1 and userid=" + shareids[i] + " and sharelevel=" + sharelevel+"  and allmanagers=0";
                    recordsql.executeSql(strtempSql);
                    if (recordsql.next()) {
                        if (recordsql.getInt(1) > 0)
                            continue;
                    }


					ProcPara = docid;
                    ProcPara += flag + sharetype;
                    ProcPara += flag + seclevel;
                    ProcPara += flag + rolelevel;
                    ProcPara += flag + sharelevel;
                    ProcPara += flag + shareids[i];
                    ProcPara += flag + subcompanyid;
                    ProcPara += flag + departmentid;
                    ProcPara += flag + roleid;
                    ProcPara += flag + foralluser;
                    ProcPara += flag + crmid; // CRMID
                    ProcPara += flag + orgGroupId; // orgGroupId

                    //record.executeProc("DocShare_IFromDocSecCategory", ProcPara);
                    /** TD12005  =========文档下载权限 开始=============*/
                     downloadlevel = String.valueOf(Util.getIntValue(recordersql.getString("downloadlevel"), 0));//TD12005
                    ProcPara += flag + downloadlevel; // 文档下载权限
                    /** TD12005  =========文档下载权限 结束=============*/
                    recordsql.executeProc("DocShare_IFromDocSecCat_G", ProcPara);               
                    recordsql.next();
                    int shareid = recordsql.getInt(1);
                     recordsql.executeSql("update docshare set isSecDefaultShare=1,allmanagers=0,includesub='"+includesub+"', orgid=0,seclevelmax='"+seclevelmax+"' where id=" + shareid);
                	
					  
					  }
                    
					continue;
						 
				   }
					
					
					
				 }
                } else if ("84".equals(sharetype)) { // 同分部
                    sharetype = "2";
					if(orgid==0){
                    subcompanyid = Util.null2String(dci.getSubcompanyid1(hrc.getDepartmentID(userid)));
					
					}else if(orgid<0){
					 recordsql.executeSql("select * from HrmResourceVirtual where virtualtype= "+orgid+" and resourceid="+userid);
					 if(recordsql.next()){
					 subcompanyid = recordsql.getString("subcompanyid");
					  
					 }
					
					}

					if(subcompanyid.equals("")||subcompanyid.equals("0")){
					            continue;
					      }

                    String strtempSql = "select count(id) from docshare where docid=" + docid
                            + " and  sharetype=2 and subcompanyid=" + subcompanyid + "" + " and seclevel=" + seclevel+" and seclevelmax='"+seclevelmax+"' and includesub='"+includesub+"'"
                            + " and sharelevel=" + sharelevel;
                    recordsql.executeSql(strtempSql);
                    if (recordsql.next()) {
                        if (recordsql.getInt(1) > 0)
                            continue;
                    }
                } else if ("85".equals(sharetype)) { // 同部门
                    sharetype = "3";
					if(orgid==0){
                    departmentid = Util.null2String(hrc.getDepartmentID(userid));
					
					}else if(orgid<0){
					   recordsql.executeSql("select * from HrmResourceVirtual where virtualtype= "+orgid+" and resourceid="+userid);
					   if(recordsql.next()){
					    departmentid = recordsql.getString("departmentid");
						
					   }
					
					}
					 if(departmentid.equals("")||departmentid.equals("0")){
					            continue;
					      }

                    String strtempSql = "select count(id) from docshare where docid=" + docid
                            + " and  sharetype=3 and departmentid=" + departmentid + "" + " and seclevel=" + seclevel+" and seclevelmax='"+seclevelmax+"' and includesub='"+includesub+"'"
                            + " and sharelevel=" + sharelevel;
                    recordsql.executeSql(strtempSql);
                    if (recordsql.next()) {
                        if (recordsql.getInt(1) > 0)
                            continue;
                    }
                } else if ("-80".equals(sharetype)) { // 创建人本人
                    sharetype = "9";
                    crmid = userid;

                    String strtempSql = "select count(id) from docshare where docid=" + docid
                            + " and  sharetype=9 and crmid=" + crmid + " and sharelevel=" + sharelevel;
                    recordsql.executeSql(strtempSql);
                    if (recordsql.next()) {
                        if (recordsql.getInt(1) > 0)
                            continue;
                    }
                } else if ("-81".equals(sharetype)) { // 创建人经理
                    sharetype = "1";
                    userid = cici.getCustomerInfomanager(userid);

                    String strtempSql = "select count(id) from docshare where docid=" + docid
                            + " and  sharetype=1 and userid=" + userid + " and sharelevel=" + sharelevel;
                    recordsql.executeSql(strtempSql);
                    if (recordsql.next()) {
                        if (recordsql.getInt(1) > 0)
                            continue;
                    }
                } else{ 
				    String strtempSql="";
					if("4".equals(sharetype)){
					 strtempSql = "select count(id) from docshare where docid='" +docid+ "' and  sharetype='"+sharetype+"' and rolelevel='"+rolelevel+"' and userid='"+userid+"' and subcompanyid='"+subcompanyid+"' and departmentid='" + departmentid + "' and roleid='"+roleid+"' and"+"  foralluser='"+foralluser+"' and crmid='"+crmid+"' and orgGroupid='"+orgGroupId+"' and downloadlevel='"+downloadlevel+"' and seclevel='" + seclevel+"' and seclevelmax='"+seclevelmax+"' and includesub='"+includesub+"'"+ " and sharelevel='" + sharelevel+"' and allmanagers='"+allmanagers+"'";
                       
					}else if("1".equals(sharetype)||"9".equals(sharetype)){
					 strtempSql = "select count(id) from docshare where docid='" +docid+ "' and  sharetype='"+sharetype+"' and userid='"+userid+"' and subcompanyid='"+subcompanyid+"' and departmentid='" + departmentid + "' and roleid='"+roleid+"' and"+"  foralluser='"+foralluser+"' and crmid='"+crmid+"' and orgGroupid='"+orgGroupId+"' and downloadlevel='"+downloadlevel+"' and includesub='"+includesub+"'"+ " and sharelevel='" + sharelevel+"' and allmanagers='"+allmanagers+"'";
				    }else{
                     strtempSql = "select count(id) from docshare where docid='" +docid+ "' and  sharetype='"+sharetype+"' and userid='"+userid+"' and subcompanyid='"+subcompanyid+"' and departmentid='" + departmentid + "' and roleid='"+roleid+"' and"+"  foralluser='"+foralluser+"' and crmid='"+crmid+"' and orgGroupid='"+orgGroupId+"' and downloadlevel='"+downloadlevel+"' and seclevel='" + seclevel+"' and seclevelmax='"+seclevelmax+"' and includesub='"+includesub+"'"+ " and sharelevel='" + sharelevel+"' and allmanagers='"+allmanagers+"'";
                    }
					recordsql.executeSql(strtempSql);			
                    if (recordsql.next()) {
                        if (recordsql.getInt(1) > 0)
                            continue;
                    }
				}

                
            		
        		List scopes = adci.getAppDetachScopes(this.userid+"");
            	if(sharetype.equals("5")&&scopes!=null&&scopes.size()>0){

        			for(int i=0;i<scopes.size();i++) {
        				Map scope = (Map) scopes.get(i);
        				sharetype = (String)scope.get("type");
        				
        				userid = "0" ;
        				departmentid = "0" ;
        				subcompanyid="0";
        				roleid = "0" ;
        				rolelevel = Util.null2o((String)scope.get("rolelevel"));
        				if(sharetype.equals("1")) userid = (String)scope.get("content");
        				if(sharetype.equals("2")) subcompanyid = (String)scope.get("content");
        				if(sharetype.equals("3")) departmentid = (String)scope.get("content");
        				if(sharetype.equals("4")) roleid = (String)scope.get("content");
        		
                        ProcPara = docid;
                        ProcPara += flag + sharetype;
                        ProcPara += flag + seclevel;
                        ProcPara += flag + rolelevel;
                        ProcPara += flag + sharelevel;
                        ProcPara += flag + userid;
                        ProcPara += flag + subcompanyid;
                        ProcPara += flag + departmentid;
                        ProcPara += flag + roleid;
                        ProcPara += flag + foralluser;
                        ProcPara += flag + crmid; // CRMID
                        ProcPara += flag + orgGroupId; // orgGroupId

                        //record.executeProc("DocShare_IFromDocSecCategory", ProcPara);
                        /** TD12005  =========文档下载权限 开始=============*/
                         downloadlevel = String.valueOf(Util.getIntValue(recordersql.getString("downloadlevel"), 0));//TD12005
                        ProcPara += flag + downloadlevel; // 文档下载权限
                        /** TD12005  =========文档下载权限 结束=============*/
                        recordsql.executeProc("DocShare_IFromDocSecCat_G", ProcPara);               
                        recordsql.next();
                        int shareid = recordsql.getInt(1);
                        recordsql.executeSql("update docshare set isSecDefaultShare=1,allmanagers='"+allmanagers+"',includesub='"+includesub+"', orgid='"+orgid+"',seclevelmax='"+seclevelmax+"' where id=" + shareid);
        			}
        		}else{

                    
                    ProcPara = docid;
                    ProcPara += flag + sharetype;
                    ProcPara += flag + seclevel;
                    ProcPara += flag + rolelevel;
                    ProcPara += flag + sharelevel;
                    ProcPara += flag + userid;
                    ProcPara += flag + subcompanyid;
                    ProcPara += flag + departmentid;
                    ProcPara += flag + roleid;
                    ProcPara += flag + foralluser;
                    ProcPara += flag + crmid; // CRMID
                    ProcPara += flag + orgGroupId; // orgGroupId

                    //record.executeProc("DocShare_IFromDocSecCategory", ProcPara);
                    /** TD12005  =========文档下载权限 开始=============*/
                     downloadlevel = String.valueOf(Util.getIntValue(recordersql.getString("downloadlevel"), 0));//TD12005
                    ProcPara += flag + downloadlevel; // 文档下载权限
                    /** TD12005  =========文档下载权限 结束=============*/
                    recordsql.executeProc("DocShare_IFromDocSecCat_G", ProcPara);               
                    recordsql.next();
                    int shareid = recordsql.getInt(1);
                    recordsql.executeSql("update docshare set isSecDefaultShare=1,allmanagers='"+allmanagers+"',includesub='"+includesub+"', orgid='"+orgid+"',seclevelmax='"+seclevelmax+"' where id=" + shareid);
                	
        		}
            }

          }
          //  setAboutCreaterShare(secid);
    }

    /**
     * 新建人力资源合同信息
     * 
     * @throws Exception
     */
    private void addHrmContract() throws Exception {
        int docid = 0;
        String sql1 = "select max(id) from DocDetail where doccreaterid=? and doccreatertype=?";
        RecordSet stat1 = new RecordSet();
        String sql = "insert into HrmContract(contractname,contractman,contracttypeid,contractstartdate,contractenddate,contractdocid,proenddate) values (?,?,?,?,?,?,?)";
        RecordSet stat = new RecordSet();
        String sqlhrm = "update HrmResource set startdate = ? , enddate = ? ,probationenddate = ? where id = ?";
        RecordSet stathrm = new RecordSet();
        try {
            stat1.executeQuery(sql1,doccreaterid,docCreaterType);
            while (stat1.next()) {
                docid = stat1.getInt(1);
            }

            stat.executeUpdate(sql,docsubject,Util.getIntValue(this.contractman, 0),typeid,contractstartdate,contractenddate,docid,proenddate);

            SysMaintenanceLog.resetParameter();
            SysMaintenanceLog.setRelatedId(docid);
            SysMaintenanceLog.setRelatedName(this.docsubject);
            SysMaintenanceLog.setOperateType("1");
            SysMaintenanceLog.setOperateDesc("HrmContract_Insert,"+this.docsubject+Util.getIntValue(this.contractman, 0));
            SysMaintenanceLog.setOperateItem("105");
            SysMaintenanceLog.setOperateUserid(this.userid);
            SysMaintenanceLog.setClientAddress(this.clientip);
            SysMaintenanceLog.setSysLogInfo();

            if (ctci.isHireContract(this.typeid)) {
                stathrm.executeUpdate(sqlhrm,contractstartdate,contractenddate,proenddate,Util.getIntValue(this.contractman, 0));
            }

        } catch (Exception e) {
            writeLog(e);
            writeLog(sql);
        } finally {
        }
    }

    /**
     * 编辑人力资源合同信息
     * 
     * @throws Exception
     */
    private void editHrmContract(String conId) throws Exception {
        String sql = "update HrmContract set contractname = ?,contractman = ?,contracttypeid = ?,contractstartdate = ?,contractenddate = ? ,proenddate = ? where contractdocid = ? ";
        String sql_HrmContractId = "update HrmContract set contractname = ?,contractman = ?,contracttypeid = ?,contractstartdate = ?,contractenddate = ? ,proenddate = ?,contractdocid = ? where id=?";       
        RecordSet stat = new RecordSet();
        String sqlhrm = "update HrmResource set startdate = ? , enddate = ? ,probationenddate = ? where id = ?";
        RecordSet stathrm = new RecordSet();
        try {
        	this.hrmContractId = this.id;
        	if(hrmContractId>0){
                stat.executeUpdate(sql_HrmContractId
                		, this.docsubject
		                , Util.getIntValue(this.contractman, 0)
		                , this.typeid
		                , this.contractstartdate
		                , this.contractenddate
		                , this.proenddate
		                , this.hrmContractId
		                , Util.getIntValue(conId,this.id)
                		);         		
        	}else{
                
                stat.executeUpdate(sql
                		, this.docsubject
		                , Util.getIntValue(this.contractman, 0)
		                , this.typeid
		                , this.contractstartdate
		                , this.contractenddate
		                , this.proenddate
		                , Util.getIntValue(conId,this.id)
                		);        		
        	}
  
            SysMaintenanceLog.resetParameter();
            SysMaintenanceLog.setRelatedId(this.id);
            SysMaintenanceLog.setRelatedName(this.docsubject);
            SysMaintenanceLog.setOperateType("2");
            SysMaintenanceLog.setOperateDesc("HrmContract_Edit,"+this.docsubject+Util.getIntValue(this.contractman, 0));
            SysMaintenanceLog.setOperateItem("105");
            SysMaintenanceLog.setOperateUserid(this.userid);
            SysMaintenanceLog.setClientAddress(this.clientip);
            SysMaintenanceLog.setSysLogInfo();

            if (ctci.isHireContract(this.typeid)) {
                stathrm.executeUpdate(sqlhrm
                		, this.contractstartdate
		                , this.contractenddate
		                , this.proenddate
		                , Util.getIntValue(this.contractman, 0)
		                );
            }
        } catch (Exception e) {
            writeLog(e);
            writeLog(sql);
        } finally {
        }
    }

    /**
     * 删除人力资源合同信息
     * 
     * @throws Exception
     */
    private synchronized void deleteHrmContract() throws Exception {
        String sql = "delete from HrmContract where contractdocid = " + this.id;
        RecordSet rssql = new RecordSet();
        try {
            rssql.executeSql(sql);

            SysMaintenanceLog.resetParameter();
            SysMaintenanceLog.setRelatedId(this.id);
            SysMaintenanceLog.setRelatedName(this.docsubject);
            SysMaintenanceLog.setOperateType("3");
            SysMaintenanceLog.setOperateDesc("HrmContract_del,"+this.docsubject+Util.getIntValue(this.contractman, 0));
            SysMaintenanceLog.setOperateItem("105");
            SysMaintenanceLog.setOperateUserid(this.userid);
            SysMaintenanceLog.setClientAddress(this.clientip);
            SysMaintenanceLog.setSysLogInfo();

        } catch (Exception e) {
            writeLog(e);
        }
    }

    /**
     * 得到文档是否可被订阅
     * 
     * @return 文档是否可被订阅
     */
    public String getOrderable() {
        return orderable;
    }

    /**
     * 设置文档是否可被订阅
     * 
     * @param orderable 文档是否可被订阅
     */
    public void setOrderable(String orderable) {
        this.orderable = orderable;
    }

    /*
     * 修改与创建人相关的默认共享 80:创建人本人 81:创建人直接上级 82:创建人间接上级 83:创建人下属 84:创建人同分部成员 85:创建人同部门成员 -80:外部用户创建人本人 -81:外部用户创建人经理
     * -82:外部用户创建人经理的上级
     */
    /**
     * 添加文档所在目录的默认共享
     * 
     * @param secId 分目录ID
     */
    public void setAboutCreaterShare(String secId) {
        int docId = this.id;
        String userId = "" + this.userid;
        RecordSet rsCreater = new RecordSet();
        char flag = 2;
        String ProcPara = "";

        String sharetype = "0";
        String seclevel = "0";
        String rolelevel = "0";
        String sharelevel = "0";
        String subcompanyid = "0";
        String departmentid = "0";
        String roleid = "0";
        String foralluser = "0";
        String crmId = "0";
        String orgGroupId = "0";

        int PCreater = 3;
        int PCreaterManager = 1;
        int PCreaterSubComp = 0;
        int PCreaterDepart = 0;
        int PCreaterSubCompLS = 0;
        int PCreaterDepartLS = 0;

        int PCreaterW = 3;
        int PCreaterManagerW = 1;

        /** TD12005 开始*/
        String PCreaterDL = "1";
        String PCreaterManagerDL = "1";
        String PCreaterSubCompDL = "0";
        String PCreaterDepartDL = "0";
        String PCreaterWDL = "1";
        String PCreaterManagerWDL = "1";
        /** TD12005 结束*/
        
        String strCreaterSql = "select * from secCreaterDocPope where secid=" + secId;
        rsCreater.executeSql(strCreaterSql);
        if (rsCreater.next()) {
            PCreater = rsCreater.getInt("PCreater");
            PCreaterManager = rsCreater.getInt("PCreaterManager");
            PCreaterSubComp = rsCreater.getInt("PCreaterSubComp");
            PCreaterDepart = rsCreater.getInt("PCreaterDepart");

            PCreaterSubCompLS = rsCreater.getInt("PCreaterSubCompLS"); // 安全级别开始数
            PCreaterDepartLS = rsCreater.getInt("PCreaterDepartLS");

            PCreaterW = rsCreater.getInt("PCreaterW");
            PCreaterManagerW = rsCreater.getInt("PCreaterManagerW");
            /** TD12005 开始*/
            PCreaterDL = String.valueOf(Util.getIntValue(rsCreater.getString("PCreaterDL"), 1));
            PCreaterManagerDL = String.valueOf(Util.getIntValue(rsCreater.getString("PCreaterManagerDL"), 1));
            PCreaterSubCompDL = String.valueOf(Util.getIntValue(rsCreater.getString("PCreaterSubCompDL"), 0));
            PCreaterDepartDL = String.valueOf(Util.getIntValue(rsCreater.getString("PCreaterDepartDL"), 0));
            PCreaterWDL = String.valueOf(Util.getIntValue(rsCreater.getString("PCreaterWDL"), 1));
            PCreaterManagerWDL = String.valueOf(Util.getIntValue(rsCreater.getString("PCreaterManagerWDL"), 1));
            /** TD12005 结束*/
        }

        // 权限 0: 无权限 1:查看权限 2:编辑权限 3:完全控制权限(包括删除等权限)
        if ("1".equals(this.usertype)) {
            // 1 对创建者本人的处理 (shareType:80)
            sharetype = "80";

            switch (PCreater) {
                case 0:
                    break;
                case 1:
                    sharelevel = "1";
                    break;
                case 2:
                    sharelevel = "2";
                    break;
                case 3:
                    sharelevel = "3";
                    break;
            }
            if (PCreater != 0) {
                ProcPara = "" + docId;
                ProcPara += flag + sharetype;
                ProcPara += flag + seclevel;
                ProcPara += flag + rolelevel;
                ProcPara += flag + sharelevel;
                ProcPara += flag + userId;
                ProcPara += flag + subcompanyid;
                ProcPara += flag + departmentid;
                ProcPara += flag + roleid;
                ProcPara += flag + foralluser;
                ProcPara += flag + crmId; // CRMID
                ProcPara += flag + orgGroupId; // orgGroupId

                //rsCreater.executeProc("DocShare_IFromDocSecCategory", ProcPara);
                /** TD12005 开始*/
                ProcPara += flag + PCreaterDL;
                /** TD12005 结束*/
                rsCreater.executeProc("DocShare_IFromDocSecCat_G", ProcPara);                
                rsCreater.next();
                int shareid = rsCreater.getInt(1);
                rsCreater.executeSql("update docshare set isSecDefaultShare=1 where id=" + shareid);

            }

            // 2 对创建者直接上级的处理 (shareType:81)
            sharetype = "81";
            switch (PCreaterManager) {
                case 0:
                    break;
                case 1:
                    sharelevel = "1";
                    break;
                case 2:
                    sharelevel = "2";
                    break;
                case 3:
                    sharelevel = "3";
                    break;
            }
            if (PCreaterManager != 0) {
                ProcPara = "" + docId;
                ProcPara += flag + sharetype;
                ProcPara += flag + seclevel;
                ProcPara += flag + rolelevel;
                ProcPara += flag + sharelevel;
                ProcPara += flag + userId;
                ProcPara += flag + subcompanyid;
                ProcPara += flag + departmentid;
                ProcPara += flag + roleid;
                ProcPara += flag + foralluser;
                ProcPara += flag + crmId; // CRMID
                ProcPara += flag + orgGroupId;
                /** TD12005 开始*/
//              rsCreater.executeProc("DocShare_IFromDocSecCategory", ProcPara);
                ProcPara += flag + PCreaterManagerDL;
                rsCreater.executeProc("DocShare_IFromDocSecCategoryDL", ProcPara);
                /** TD12005 结束*/
                rsCreater.next();
                int shareid = rsCreater.getInt(1);
                rsCreater.executeSql("update docshare set isSecDefaultShare=1 where id=" + shareid);
            }
            // 5 对创建者同分部的处理 (shareType:84)
            sharetype = "84";
            switch (PCreaterSubComp) {
                case 0:
                    break;
                case 1:
                    sharelevel = "1";
                    break;
                case 2:
                    sharelevel = "2";
                    break;
                case 3:
                    sharelevel = "3";
                    break;
            }
            if (PCreaterSubComp != 0) {
                ProcPara = "" + docId;
                ProcPara += flag + sharetype;
                ProcPara += flag + "" + PCreaterSubCompLS;
                ProcPara += flag + rolelevel;
                ProcPara += flag + sharelevel;
                ProcPara += flag + userId;
                ProcPara += flag + subcompanyid;
                ProcPara += flag + departmentid;
                ProcPara += flag + roleid;
                ProcPara += flag + foralluser;
                ProcPara += flag + crmId; // CRMID
                ProcPara += flag + orgGroupId;
                /** TD12005 开始*/
//              rsCreater.executeProc("DocShare_IFromDocSecCategory", ProcPara);
                ProcPara += flag + PCreaterSubCompDL;
                rsCreater.executeProc("DocShare_IFromDocSecCategoryDL", ProcPara);
                /** TD12005 结束*/
                rsCreater.next();
                int shareid = rsCreater.getInt(1);
                rsCreater.executeSql("update docshare set isSecDefaultShare=1 where id=" + shareid);
            }
            // 6 对创建都同部门的处理 (shareType:85)
            sharetype = "85";
            switch (PCreaterDepart) {
                case 0:
                    break;
                case 1:
                    sharelevel = "1";
                    break;
                case 2:
                    sharelevel = "2";
                    break;
                case 3:
                    sharelevel = "3";
                    break;
            }
            if (PCreaterDepart != 0) {
                ProcPara = "" + docId;
                ProcPara += flag + sharetype;
                ProcPara += flag + "" + PCreaterDepartLS;
                ProcPara += flag + rolelevel;
                ProcPara += flag + sharelevel;
                ProcPara += flag + userId;
                ProcPara += flag + subcompanyid;
                ProcPara += flag + departmentid;
                ProcPara += flag + roleid;
                ProcPara += flag + foralluser;
                ProcPara += flag + crmId; // CRMID
                ProcPara += flag + orgGroupId;
                /** TD12005 开始*/
//              rsCreater.executeProc("DocShare_IFromDocSecCategory", ProcPara);
                ProcPara += flag + PCreaterDepartDL;
                rsCreater.executeProc("DocShare_IFromDocSecCategoryDL", ProcPara);
                /** TD12005 结束*/
                rsCreater.next();
                int shareid = rsCreater.getInt(1);
                rsCreater.executeSql("update docshare set isSecDefaultShare=1 where id=" + shareid);
            }
        } else {
            // 7 对外部创建者的处理 (shareType:-80)
            sharetype = "-80";
            switch (PCreaterW) {
                case 0:
                    break;
                case 1:
                    sharelevel = "1";
                    break;
                case 2:
                    sharelevel = "2";
                    break;
                case 3:
                    sharelevel = "3";
                    break;
            }
            if (PCreaterW != 0) {
                ProcPara = "" + docId;
                ProcPara += flag + sharetype;
                ProcPara += flag + "" + PCreaterW;
                ProcPara += flag + rolelevel;
                ProcPara += flag + sharelevel;
                ProcPara += flag + userId;
                ProcPara += flag + subcompanyid;
                ProcPara += flag + departmentid;
                ProcPara += flag + roleid;
                ProcPara += flag + foralluser;
                ProcPara += flag + crmId; // CRMID
                ProcPara += flag + orgGroupId;
                /** TD12005 开始*/
//              rsCreater.executeProc("DocShare_IFromDocSecCategory", ProcPara);
                ProcPara += flag + PCreaterWDL;
                rsCreater.executeProc("DocShare_IFromDocSecCategoryDL", ProcPara);
                /** TD12005 结束*/
                rsCreater.next();
                int shareid = rsCreater.getInt(1);
                rsCreater.executeSql("update docshare set isSecDefaultShare=1 where id=" + shareid);
            }
            // 8 对外部创建者的经理的处理 (shareType:-81)
            sharetype = "-81";
            switch (PCreaterManagerW) {
                case 0:
                    break;
                case 1:
                    sharelevel = "1";
                    break;
                case 2:
                    sharelevel = "2";
                    break;
                case 3:
                    sharelevel = "3";
                    break;
            }
            if (PCreaterManagerW != 0) {
                ProcPara = "" + docId;
                ProcPara += flag + sharetype;
                ProcPara += flag + "" + PCreaterManagerW;
                ProcPara += flag + rolelevel;
                ProcPara += flag + sharelevel;
                ProcPara += flag + userId;
                ProcPara += flag + subcompanyid;
                ProcPara += flag + departmentid;
                ProcPara += flag + roleid;
                ProcPara += flag + foralluser;
                ProcPara += flag + crmId; // CRMID
                ProcPara += flag + orgGroupId;
                /** TD12005 开始*/
//              rsCreater.executeProc("DocShare_IFromDocSecCategory", ProcPara);
                ProcPara += flag + PCreaterManagerWDL;
                rsCreater.executeProc("DocShare_IFromDocSecCategoryDL", ProcPara);
                /** TD12005 结束*/
                rsCreater.next();
                int shareid = rsCreater.getInt(1);
                rsCreater.executeSql("update docshare set isSecDefaultShare=1 where id=" + shareid);
            }
        }
    }

    /**
     * 返回操作类型
     * 
     * @return 操作类型
     */
    public String getOpreateType() {
        return opreateType;
    }

    /**
     * 设置操作类型
     * 
     * @param opreateType
     */
    public void setOpreateType(String opreateType) {
        this.opreateType = opreateType;
    }

    
    
    /**
     * @return the docCancelDate
     */
    public String getDocCancelDate() {
        return rs.getString("docCancelDate");
    }

    /**
     * @return the docCancelTime
     */
    public String getDocCancelTime() {
        return rs.getString("docCancelTime");
    }

    /**
     * @return the docCancelUserId
     */
    public int getDocCancelUserId() {
        return rs.getInt("docCancelUserId");
    }

    /**
     * @return the docCode
     */
    public String getDocCode() {
        return rs.getString("docCode");
    }

    /**
     * @return the docEdition
     */
    public int getDocEdition() {
        return rs.getInt("docEdition");
    }

    /**
     * @return the docEditionId
     */
    public int getDocEditionId() {
        return rs.getInt("docEditionId");
    }

    /**
     * @return the isHistory
     */
    public int getIsHistory() {
        return Util.getIntValue(rs.getString("isHistory"),0);
    }
    
    /**
     * @return the approveType
     */
    public int getApproveType() {
        return Util.getIntValue(rs.getString("approveType"),0);
    }
    
    /**
     * @return the selectedPubMouldId
     */
    public int getSelectedPubMouldId() {
        return Util.getIntValue(rs.getString("selectedPubMouldId"),0);
    }
    
    /**
     * @return the docInvalDate
     */
    public String getDocInvalDate() {
        return rs.getString("docInvalDate");
    }

    /**
     * @return the docInvalTime
     */
    public String getDocInvalTime() {
        return rs.getString("docInvalTime");
    }

    /**
     * @return the docInvalUserId
     */
    public int getDocInvalUserId() {
        return rs.getInt("docInvalUserId");
    }

    /**
     * @return the docReOpenDate
     */
    public String getDocReOpenDate() {
        return rs.getString("docReOpenDate");
    }

    /**
     * @return the docReOpenTime
     */
    public String getDocReOpenTime() {
        return rs.getString("docReOpenTime");
    }

    /**
     * @return the docReOpenUserId
     */
    public int getDocReOpenUserId() {
        return rs.getInt("docReOpenUserId");
    }

    /**
     * @return the docPubDate
     */
    public String getDocPubDate() {
        return rs.getString("docPubDate");
    }

    /**
     * @return the docPubTime
     */
    public String getDocPubTime() {
        return rs.getString("docPubTime");
    }

    /**
     * @return the docPubUserId
     */
    public int getDocPubUserId() {
        return rs.getInt("docPubUserId");
    }

    /**
     * @return the docValidDate
     */
    public String getDocValidDate() {
        return rs.getString("docValidDate");
    }

    /**
     * @return the docValidTime
     */
    public String getDocValidTime() {
        return rs.getString("docValidTime");
    }

    /**
     * @return the docValidUserId
     */
    public int getDocValidUserId() {
        return rs.getInt("docValidUserId");
    }

    /**
     * @return the mainDoc
     */
    public int getMainDoc() {
        return rs.getInt("mainDoc");
    }

    /**
     * @return the readOpterCanPrint
     */
    public int getReadOpterCanPrint() {
        return rs.getInt("readOpterCanPrint");
    }

    /**
     * @return the invalidationDate
     */
    public String getInvalidationDate() {
        return rs.getString("invalidationdate");
    }

    
    /**
     * @return the checkOutStatus
     */
    public String getCheckOutStatus() {
        return rs.getString("checkOutStatus");
    }   
    
    /**
     * @return the checkOutUserId
     */
    public int getCheckOutUserId() {
        return rs.getInt("checkOutUserId");
    }
    
    /**
     * @return the checkOutUserType
     */
    public String getCheckOutUserType() {
        return rs.getString("checkOutUserType");
    }       
    
    /**
     * @return the checkOutDate
     */
    public String getCheckOutDate() {
        return rs.getString("checkOutDate");
    }       
    
    /**
     * @return the checkOutTime
     */
    public String getCheckOutTime() {
        return rs.getString("checkOutTime");
    }       
    
    /**
     * @return the hasUsedTemplet  返回  是否已经套红
     */
    public String getHasUsedTemplet() {
        return rs.getString("hasUsedTemplet");
    } 
    
    /**
     * @return the docCreaterType  返回  文档创建者类型（1:内部用户  2：外部用户）
     */
    public String getDocCreaterType() {
        return rs.getString("docCreaterType");
    } 
    
    /**
     * @return the docLastModUserType  返回  文档最后修改者类型（1:内部用户  2：外部用户）
     */
    public String getDocLastModUserType() {
        return rs.getString("docLastModUserType");
    } 
    
    /**
     * @return the docApproveUserType  返回  文档审批者类型（1:内部用户  2：外部用户）
     */
    public String getDocApproveUserType() {
        return rs.getString("docApproveUserType");
    } 
    
    /**
     * @return the docValidUserType  返回  生效操作人类型（1:内部用户  2：外部用户）
     */
    public String getDocValidUserType() {
        return rs.getString("docValidUserType");
    } 
    
    /**
     * @return the docInvalUserType  返回  失效操作人类型（1:内部用户  2：外部用户）
     */
    public String getDocInvalUserType() {
        return rs.getString("docInvalUserType");
    } 
    
    /**
     * @return the docArchiveUserType  返回  文档归档者类型（1:内部用户  2：外部用户）
     */
    public String getDocArchiveUserType() {
        return rs.getString("docArchiveUserType");
    } 
    
    /**
     * @return the docCancelUserType  返回  作废操作人类型（1:内部用户  2：外部用户）
     */
    public String getDocCancelUserType() {
        return rs.getString("docCancelUserType");
    } 
    
    /**
     * @return the docPubUserType  返回  发布操作人类型（1:内部用户  2：外部用户）
     */
    public String getDocPubUserType() {
        return rs.getString("docPubUserType");
    } 
    
    /**
     * @return the docReopenUserType  返回  重新打开操作人类型（1:内部用户  2：外部用户）
     */
    public String getDocReopenUserType() {
        return rs.getString("docReopenUserType");
    } 
     
    /**
     * @return the ownerType  返回  文档拥有者类型（1:内部用户  2：外部用户）
     */
    public String getOwnerType() {
        return rs.getString("ownerType");
    }    
    
    /**
     * @return the docCancelDate
     */
    public String getDocCancelDate2() {
        return docCancelDate;
    }

    /**
     * @return the docCancelTime
     */
    public String getDocCancelTime2() {
        return docCancelTime;
    }

    /**
     * @return the docCancelUserId
     */
    public int getDocCancelUserId2() {
        return docCancelUserId;
    }

    /**
     * @return the docCode
     */
    public String getDocCode2() {
        return docCode;
    }

    /**
     * @return the docEdition
     */
    public int getDocEdition2() {
        return docEdition;
    }

    /**
     * @return the isHistory
     */
    public int getIsHistory2() {
        return isHistory;
    }
    
    /**
     * @return the approveType
     */
    public int getApproveType2() {
        return approveType;
    }
    
    /**
     * @return the selectedPubMouldId
     */
    public int getSelectedPubMouldId2() {
        return selectedPubMouldId;
    }

    /**
     * @return the docEditionId
     */
    public int getDocEditionId2() {
        return docEditionId;
    }

    /**
     * @return the docInvalDate
     */
    public String getDocInvalDate2() {
        return docInvalDate;
    }

    /**
     * @return the docInvalTime
     */
    public String getDocInvalTime2() {
        return docInvalTime;
    }

    /**
     * @return the docInvalUserId
     */
    public int getDocInvalUserId2() {
        return docInvalUserId;
    }

    /**
     * @return the docReOpenDate
     */
    public String getDocReOpenDate2() {
        return docReOpenDate;
    }

    /**
     * @return the docReOpenTime
     */
    public String getDocReOpenTime2() {
        return docReOpenTime;
    }

    /**
     * @return the docReOpenUserId
     */
    public int getDocReOpenUserId2() {
        return docReOpenUserId;
    }

    /**
     * @return the docPubDate
     */
    public String getDocPubDate2() {
        return docPubDate;
    }

    /**
     * @return the docPubTime
     */
    public String getDocPubTime2() {
        return docPubTime;
    }

    /**
     * @return the docPubUserId
     */
    public int getDocPubUserId2() {
        return docPubUserId;
    }

    /**
     * @return the docValidDate
     */
    public String getDocValidDate2() {
        return docValidDate;
    }

    /**
     * @return the docValidTime
     */
    public String getDocValidTime2() {
        return docValidTime;
    }

    /**
     * @return the docValidUserId
     */
    public int getDocValidUserId2() {
        return docValidUserId;
    }

    /**
     * @return the mainDoc
     */
    public int getMainDoc2() {
        return mainDoc;
    }

    /**
     * @return the readOpterCanPrint
     */
    public int getReadOpterCanPrint2() {
        return readOpterCanPrint;
    }

    /**
     * @return the invalidationDate
     */
    public String getInvalidationDate2() {
        return invalidationDate;
    }
    

   
    /**
     * @param docCancelDate the docCancelDate to set
     */
    public void setDocCancelDate(String docCancelDate) {
        this.docCancelDate = docCancelDate;
    }

    /**
     * @param docCancelTime the docCancelTime to set
     */
    public void setDocCancelTime(String docCancelTime) {
        this.docCancelTime = docCancelTime;
    }

    /**
     * @param docCancelUserId the docCancelUserId to set
     */
    public void setDocCancelUserId(int docCancelUserId) {
        this.docCancelUserId = docCancelUserId;
    }

    /**
     * @param docCode the docCode to set
     */
    public void setDocCode(String docCode) {
        this.docCode = docCode;
    }

    /**
     * @param docEdition the docEdition to set
     */
    public void setDocEdition(int docEdition) {
        this.docEdition = docEdition;
    }

    /**
     * @param docEdition the docEditionId to set
     */
    public void setDocEditionId(int docEditionId) {
        this.docEditionId = docEditionId;
    }

    /**
     * @param isHistory the isHistory to set
     */
    public void setIsHistory(int isHistory) {
        this.isHistory = isHistory;
    }
    
    /**
     * @param approveType the approveType to set
     */
    public void setApproveType(int approveType) {
        this.approveType = approveType;
    }
        
    /**
     * @param selectedPubMouldId the selectedPubMouldId to set
     */
    public void setSelectedPubMouldId(int selectedPubMouldId) {
        this.selectedPubMouldId = selectedPubMouldId;
    }
    
    /**
     * @param docInvalDate the docInvalDate to set
     */
    public void setDocInvalDate(String docInvalDate) {
        this.docInvalDate = docInvalDate;
    }

    /**
     * @param docInvalTime the docInvalTime to set
     */
    public void setDocInvalTime(String docInvalTime) {
        this.docInvalTime = docInvalTime;
    }

    /**
     * @param docInvalUserId the docInvalUserId to set
     */
    public void setDocInvalUserId(int docInvalUserId) {
        this.docInvalUserId = docInvalUserId;
    }

    /**
     * @param docReOpenDate the docReOpenDate to set
     */
    public void setDocReOpenDate(String docReOpenDate) {
        this.docReOpenDate = docReOpenDate;
    }

    /**
     * @param docReOpenTime the docReOpenTime to set
     */
    public void setDocReOpenTime(String docReOpenTime) {
        this.docReOpenTime = docReOpenTime;
    }

    /**
     * @param docReOpenUserId the docReOpenUserId to set
     */
    public void setDocReOpenUserId(int docReOpenUserId) {
        this.docReOpenUserId = docReOpenUserId;
    }

    /**
     * @param docPubDate the DocPubDate to set
     */
    public void setDocPubDate(String docPubDate) {
        this.docPubDate = docPubDate;
    }

    /**
     * @param DocPubTime the DocPubTime to set
     */
    public void setDocPubTime(String docPubTime) {
        this.docPubTime = docPubTime;
    }

    /**
     * @param DocPubUserId the DocPubUserId to set
     */
    public void setDocPubUserId(int docPubUserId) {
        this.docPubUserId = docPubUserId;
    }

    /**
     * @param docValidDate the docValidDate to set
     */
    public void setDocValidDate(String docValidDate) {
        this.docValidDate = docValidDate;
    }

    /**
     * @param docValidTime the docValidTime to set
     */
    public void setDocValidTime(String docValidTime) {
        this.docValidTime = docValidTime;
    }

    /**
     * @param docValidUserId the docValidUserId to set
     */
    public void setDocValidUserId(int docValidUserId) {
        this.docValidUserId = docValidUserId;
    }

    /**
     * @param mainDoc the mainDoc to set
     */
    public void setMainDoc(int mainDoc) {
        this.mainDoc = mainDoc;
    }

    /**
     * @param readOpterCanPrint the readOpterCanPrint to set
     */
    public void setReadOpterCanPrint(int readOpterCanPrint) {
        this.readOpterCanPrint = readOpterCanPrint;
    }
    
    /**
     * @param invalidationDate the invalidationDate to set
     */
    public void setInvalidationDate(String invalidationDate) {
        this.invalidationDate = invalidationDate;
    }
    
	 public void setDummycata(String dummycata) {
        this.dummycata = dummycata;
    }

    
    /**
     * @param  docCreaterType  设置  文档创建者类型（1:内部用户  2：外部用户）
     */
    public void setDocCreaterType(String paraValue) {
    	this.docCreaterType=paraValue;
    } 
    
    /**
     * @param  docLastModUserType  设置  文档最后修改者类型（1:内部用户  2：外部用户）
     */
    public void setDocLastModUserType(String paraValue) {
    	this.docLastModUserType=paraValue;
    } 
    
    /**
     * @param  docApproveUserType  设置  文档审批者类型（1:内部用户  2：外部用户）
     */
    public void setDocApproveUserType(String paraValue) {
    	this.docApproveUserType=paraValue;
    } 
    
    /**
     * @param  docValidUserType  设置  生效操作人类型（1:内部用户  2：外部用户）
     */
    public void setDocValidUserType(String paraValue) {
    	this.docValidUserType=paraValue;
    } 
    
    /**
     * @param  docInvalUserType  设置  失效操作人类型（1:内部用户  2：外部用户）
     */
    public void setDocInvalUserType(String paraValue) {
    	this.docInvalUserType=paraValue;
    } 
    
    /**
     * @param  docArchiveUserType  设置  文档归档者类型（1:内部用户  2：外部用户）
     */
    public void setDocArchiveUserType(String paraValue) {
    	this.docArchiveUserType=paraValue;
    } 
    
    /**
     * @param  docCancelUserType  设置  作废操作人类型（1:内部用户  2：外部用户）
     */
    public void setDocCancelUserType(String paraValue) {
    	this.docCancelUserType=paraValue;
    } 
    
    /**
     * @param  docPubUserType  设置  发布操作人类型（1:内部用户  2：外部用户）
     */
    public void setDocPubUserType(String paraValue) {
    	this.docPubUserType=paraValue;
    } 
    
    /**
     * @param  docReopenUserType  设置  重新打开操作人类型（1:内部用户  2：外部用户）
     */
    public void setDocReopenUserType(String paraValue) {
    	this.docReopenUserType=paraValue;
    } 
     
    /**
     * @param  ownerType  设置  文档拥有者类型（1:内部用户  2：外部用户）
     */
    public void setOwnerType(String paraValue) {
    	this.ownerType=paraValue;
    }    
     
    
    /**
     * 流程审批文档
     * @param type 审批类型("reject","approve")
     * @param docId 文档ID
     * @param approveDate 审批日期
     * @param approveTime 审批时间
     * @param userId 审批用户
     */
    public void approveDocFromWF(String type,String docId,String approveDate,String approveTime,String userId) throws Exception {
    	
    	//安全性检查
    	if(type==null
    	 ||(!"reject".equals(type)&&!"approve".equals(type))
     	 ||docId==null
     	 ||Util.getIntValue(docId,-1)<=0
    	){
    		return ;
    	}
    	
        RecordSet rs = new RecordSet();
        
        this.id = Util.getIntValue(docId);
        this.getDocInfoById();
        this.maincategory = this.getMaincategory();
        this.subcategory = this.getSubcategory();
        this.seccategory = this.getSeccategory();
        this.docstatus = this.getDocstatus();
        this.docEdition = this.getDocEdition();
        this.docEditionId = this.getDocEditionId();
        this.approveType = this.getApproveType();
        this.docsubject=this.getDocsubject();
        this.doccreaterid=this.getDoccreaterid();
        //String createrType=this.getUsertype();
        this.docCreaterType=this.getDocCreaterType(); 
        
        this.usertype=(this.usertype==null||this.usertype.trim().equals(""))?"1":this.usertype;
        
        String operateType="4";
        
        if(type.equals("reject")){
            //this.docstatus = "4";
        	//如果为失效审批，则退回后文档状态为“2：生效/正常”,否则为“4：退回”
        	if(this.approveType==2){
        		this.docstatus="2";
        	}else{
        		this.docstatus="4";
        	}
            operateType="5";//操作的类型：5：退回
            
            rs.executeSql(
                    " UPDATE DocDetail SET " +
                    " docstatus = " + this.docstatus +
                    ",docapproveuserid = " + userId +
                    ",docApproveUserType = '" + this.usertype +  "'" +                           
                    ",docapprovedate = '" + approveDate + "'" +
                    ",docapprovetime = '" + approveTime + "'" +    
                    " WHERE ID = " + this.id
            );            
        }else if(type.equals("approve")){
            operateType="4";//操作的类型：4：批准       	
            if(this.approveType==1){//生效审批
                if(scc.needPubOperation(this.seccategory)) {//如果需要发布
                    this.docstatus = "6";
                    rs.executeSql(
                            " UPDATE DocDetail SET " +
                            " docstatus = " + this.docstatus +
                            ",docapproveuserid = " + userId +
                            ",docApproveUserType = '" + this.usertype +  "'" +                           
                            ",docapprovedate = '" + approveDate + "'" +
                            ",docapprovetime = '" + approveTime + "'" +    
                            " WHERE ID = " + this.id
                    );                    
                } else {//生效/正常
                    this.docstatus = "2";
    
                    if(scc.isEditionOpen(this.seccategory)) {//如果版本管理开启
                        if(this.docEditionId==-1)
                            this.docEditionId = this.getNextEditionId(rs);
                        this.docEdition = dc.getEdition(this.docEditionId)+1;
                        rs.executeSql(" update docdetail set docstatus = 7,ishistory = 1 where id <> " + this.id + " and docedition > 0 and docedition < " + this.docEdition + " and doceditionid > 0 and doceditionid = " + this.docEditionId);
                        
                        rs.executeSql(" select id from docdetail where id <> " + this.id + " and docedition < " + this.docEdition + " and doceditionid = " + this.docEditionId + " order by docEdition desc ");
                        if(rs.next()){
                            int oldDocId = rs.getInt("id");
                        
                            log.resetParameter();
                            log.setDocId(oldDocId);
                            log.setDocSubject(this.docsubject);
                            log.setOperateType("14");
                            log.setOperateUserid(userid);
                            log.setUsertype(this.usertype);
                            log.setClientAddress(this.clientip);
                            log.setDocCreater(this.doccreaterid);
                            //log.setCreatertype(createrType);
                            log.setCreatertype(this.docCreaterType);                              
                            log.setDocLogInfo();
                        }
                    }
    
                    rs.executeSql(
                            " UPDATE DocDetail SET " +
                            " docstatus = " + this.docstatus +
                            ",docEdition = " + this.docEdition +
                            ",docEditionId = " + this.docEditionId +
                            ",docapproveuserid = " + userId +
                            ",docApproveUserType = '" + this.usertype +  "'" +                           
                            ",docapprovedate = '" + approveDate + "'" +
                            ",docapprovetime = '" + approveTime + "'" +
                            ",docvaliduserid = " + userId +
                            ",docValidUserType = '" + this.usertype +  "'" +                               
                            ",docvaliddate = '" + approveDate + "'" +
                            ",docvalidtime = '" + approveTime + "'" +
                            " WHERE ID = " + docId
                    );


                }
            } else if(this.approveType==2){//失效审批
                this.docstatus = "7";
                this.docInvalUserId = this.userid;
                this.docInvalUserType = this.usertype;
                this.docInvalDate = approveDate;
                this.docInvalTime = approveTime;
                    
                if(scc.isEditionOpen(this.seccategory)) {//如果版本管理开启
                    if(this.docEditionId==-1)
                        this.docEditionId = this.getNextEditionId(rs);
                    //this.docEdition = dc.getEdition(this.docEditionId)+1;
                    this.docEdition = dc.getEdition(this.docEditionId);                   
                    rs.executeSql(" update docdetail set docstatus = 7,ishistory = 1 where id <> " + this.id + " and docedition > 0 and docedition < " + this.docEdition + " and doceditionid > 0 and doceditionid = " + this.docEditionId);
                }
                
                rs.executeSql(
                        " UPDATE DocDetail SET " +
                        " docstatus = " + this.docstatus +
                        ",approvetype = " + this.approveType +
                        ",docEdition = " + this.docEdition +
                        ",docEditionId = " + this.docEditionId +
                        ",docapproveuserid = " + userId +
                        ",docApproveUserType = '" + this.usertype +  "'" +                           
                        ",docapprovedate = '" + approveDate + "'" +
                        ",docapprovetime = '" + approveTime + "'" +                        
                        ",docinvaluserid = " + this.docInvalUserId +
                        ",docInvalUserType = '" + this.docInvalUserType + "'" +                       
                        ",docinvaldate = '" + this.docInvalDate + "'" +
                        ",docinvaltime = '" + this.docInvalTime + "'" +
                        " WHERE ID = " + this.id
                );
            }
        }
        
        //char flag=Util.getSeparator();
        //String para=userId+flag+this.docstatus+flag+approveDate+flag+approveTime+flag+docId;
        //rs.executeProc("DocDetail_Approve",para);
        
        log.resetParameter();
        log.setDocId(this.id);
        log.setDocSubject(this.docsubject);
        log.setOperateType(operateType);
        log.setOperateUserid(this.userid);
        log.setUsertype(this.usertype);
        log.setClientAddress(this.clientip);
        log.setDocCreater(this.doccreaterid);
        //log.setCreatertype(createrType);
        log.setCreatertype(this.docCreaterType);          
        log.setDocLogInfo();
        if(this.docstatus.equals("2") || this.docstatus.equals("1") || this.docstatus.equals("5")){
            //RecordSet rsforsend = new RecordSet();
          //  rsforsend.executeSql("select shareids from sendtoalltemp where status = 0 and docid=" + docId);
          //  while (rsforsend.next()) {
              //  String shareids = Util.null2String(rsforsend.getString("shareids"));
                ThreadForAllForNew sendToAllfornew = new ThreadForAllForNew(docId,"",userId);
                sendToAllfornew.start();
           // }
        }
        
    }


	  public void approveDocFromWFGD(String type,String docId,String approveDate,String approveTime,String userId) throws Exception {
    	
    	//安全性检查
    	if(type==null
    	 ||(!"reject".equals(type)&&!"approve".equals(type))
     	 ||docId==null
     	 ||Util.getIntValue(docId,-1)<=0
    	){
    		return ;
    	}
    	
        RecordSet rs = new RecordSet();
		rs.writeLog("++++++++++++++++approveDocFromWF.type=="+type);
		rs.writeLog("++++++++++++++++approveDocFromWF.docId=="+docId);
		rs.writeLog("++++++++++++++++approveDocFromWF.approveDate=="+approveDate);
		rs.writeLog("++++++++++++++++approveDocFromWF.approveTime=="+approveTime);
		rs.writeLog("++++++++++++++++approveDocFromWF.userId=="+userId);
        
        this.id = Util.getIntValue(docId);
        this.getDocInfoById();
        this.maincategory = this.getMaincategory();
        this.subcategory = this.getSubcategory();
        this.seccategory = this.getSeccategory();
        this.docstatus = this.getDocstatus();
        this.docEdition = this.getDocEdition();
        this.docEditionId = this.getDocEditionId();
        this.approveType = this.getApproveType();
        this.docsubject=this.getDocsubject();
        this.doccreaterid=this.getDoccreaterid();
        //String createrType=this.getUsertype();
        this.docCreaterType=this.getDocCreaterType(); 
        
        this.usertype=(this.usertype==null||this.usertype.trim().equals(""))?"1":this.usertype;
        
        String operateType="4";
        
        if(type.equals("approve")){
            operateType="4";//操作的类型：4：批准       	
            if(this.approveType==1){//生效审批
                if(scc.needPubOperation(this.seccategory)) {//如果需要发布
                    this.docstatus = "6";
                    rs.executeSql(
                            " UPDATE DocDetail SET " +
                            " docstatus = " + this.docstatus +
                            ",docapproveuserid = " + userId +
                            ",docApproveUserType = '" + this.usertype +  "'" +                           
                            ",docapprovedate = '" + approveDate + "'" +
                            ",docapprovetime = '" + approveTime + "'" +    
                            " WHERE ID = " + this.id
                    ); 
					rs.writeLog("++++++++++++++++ fabusql== UPDATE DocDetail SET " +
                            " docstatus = " + this.docstatus +
                            ",docapproveuserid = " + userId +
                            ",docApproveUserType = '" + this.usertype +  "'" +                           
                            ",docapprovedate = '" + approveDate + "'" +
                            ",docapprovetime = '" + approveTime + "'" +    
                            " WHERE ID = " + this.id
                    ); 
					
                } else {//生效/正常
                    this.docstatus = "2";
    
                    if(scc.isEditionOpen(this.seccategory)) {//如果版本管理开启
						rs.writeLog("++++++++++++++++isEditionOpen");
                        if(this.docEditionId==-1)
                            this.docEditionId = this.getNextEditionId(rs);
                        this.docEdition = dc.getEdition(this.docEditionId)+1;
                        rs.executeSql(" update docdetail set docstatus = 7,ishistory = 1 where id <> " + this.id + " and docedition > 0 and docedition < " + this.docEdition + " and doceditionid > 0 and doceditionid = " + this.docEditionId);
                        
                        rs.executeSql(" select id from docdetail where id <> " + this.id + " and docedition < " + this.docEdition + " and doceditionid = " + this.docEditionId + " order by docEdition desc ");
                        if(rs.next()){
                            int oldDocId = rs.getInt("id");
                        
                            log.resetParameter();
                            log.setDocId(oldDocId);
                            log.setDocSubject(this.docsubject);
                            log.setOperateType("14");
                            log.setOperateUserid(userid);
                            log.setUsertype(this.usertype);
                            log.setClientAddress(this.clientip);
                            log.setDocCreater(this.doccreaterid);
                            //log.setCreatertype(createrType);
                            log.setCreatertype(this.docCreaterType);                              
                            log.setDocLogInfo();
                        }
                    }
    
                    rs.executeSql(
                            " UPDATE DocDetail SET " +
                            " docstatus = " + this.docstatus +
                            ",docEdition = " + this.docEdition +
                            ",docEditionId = " + this.docEditionId +
                            ",docapproveuserid = " + userId +
                            ",docApproveUserType = '" + this.usertype +  "'" +                           
                            ",docapprovedate = '" + approveDate + "'" +
                            ",docapprovetime = '" + approveTime + "'" +
                            ",docvaliduserid = " + userId +
                            ",docValidUserType = '" + this.usertype +  "'" +                               
                            ",docvaliddate = '" + approveDate + "'" +
                            ",docvalidtime = '" + approveTime + "'" +
                            ",docarchiveuserid = " + userId +
                            ",docArchiveUserType = '" + this.usertype +  "'" +   
						    						",docarchivedate = '" + approveDate + "'" +
                            ",docarchivetime = '" + approveTime + "'" +
                            " WHERE ID = " + docId
                    );
										rs.writeLog("++++++++++++++++zhengchangsql=== UPDATE DocDetail SET " +
                            " docstatus = " + this.docstatus +
                            ",docEdition = " + this.docEdition +
                            ",docEditionId = " + this.docEditionId +
                            ",docapproveuserid = " + userId +
                            ",docApproveUserType = '" + this.usertype +  "'" +                           
                            ",docapprovedate = '" + approveDate + "'" +
                            ",docapprovetime = '" + approveTime + "'" +
                            ",docvaliduserid = " + userId +
                            ",docValidUserType = '" + this.usertype +  "'" +                               
                            ",docvaliddate = '" + approveDate + "'" +
                            ",docvalidtime = '" + approveTime + "'" +
                            " WHERE ID = " + docId
                    );

                }
            } else if(this.approveType==2){//失效审批
                this.docstatus = "7";
                this.docInvalUserId = this.userid;
                this.docInvalUserType = this.usertype;
                this.docInvalDate = approveDate;
                this.docInvalTime = approveTime;
                    
                if(scc.isEditionOpen(this.seccategory)) {//如果版本管理开启
                    if(this.docEditionId==-1)
                        this.docEditionId = this.getNextEditionId(rs);
                    //this.docEdition = dc.getEdition(this.docEditionId)+1;
                    this.docEdition = dc.getEdition(this.docEditionId);                   
                    rs.executeSql(" update docdetail set docstatus = 7,ishistory = 1 where id <> " + this.id + " and docedition > 0 and docedition < " + this.docEdition + " and doceditionid > 0 and doceditionid = " + this.docEditionId);
                }
                
                rs.executeSql(
                        " UPDATE DocDetail SET " +
                        " docstatus = " + this.docstatus +
                        ",approvetype = " + this.approveType +
                        ",docEdition = " + this.docEdition +
                        ",docEditionId = " + this.docEditionId +
                        ",docapproveuserid = " + userId +
                        ",docApproveUserType = '" + this.usertype +  "'" +                           
                        ",docapprovedate = '" + approveDate + "'" +
                        ",docapprovetime = '" + approveTime + "'" +                        
                        ",docinvaluserid = " + this.docInvalUserId +
                        ",docInvalUserType = '" + this.docInvalUserType + "'" +                       
                        ",docinvaldate = '" + this.docInvalDate + "'" +
                        ",docinvaltime = '" + this.docInvalTime + "'" +
                        " WHERE ID = " + this.id
                );
            }
        }
        
        //char flag=Util.getSeparator();
        //String para=userId+flag+this.docstatus+flag+approveDate+flag+approveTime+flag+docId;
        //rs.executeProc("DocDetail_Approve",para);
        
        log.resetParameter();
        log.setDocId(this.id);
        log.setDocSubject(this.docsubject);
        log.setOperateType(operateType);
        log.setOperateUserid(this.userid);
        log.setUsertype(this.usertype);
        log.setClientAddress(this.clientip);
        log.setDocCreater(this.doccreaterid);
        //log.setCreatertype(createrType);
        log.setCreatertype(this.docCreaterType);          
        log.setDocLogInfo();

        if(this.docstatus.equals("2") || this.docstatus.equals("1") || this.docstatus.equals("5")){
            //  RecordSet rsforsend = new RecordSet();
            //  rsforsend.executeSql("select shareids from sendtoalltemp where status = 0 and docid=" + this.id);
           //   while (rsforsend.next()) {
           //       String shareids = Util.null2String(rsforsend.getString("shareids"));
                  ThreadForAllForNew sendToAllfornew = new ThreadForAllForNew(this.id+"", "",this.userid+"");
                  sendToAllfornew.start();
            //  }
          }

    }
    
    /**
     * 发布文档
     * @param fu FileUpload对象
     * @throws Exception
     */
    public void publishDoc(FileUpload fu) throws Exception {
        RecordSet rs = new RecordSet();
        
        this.id = Util.getIntValue(fu.getParameter("id"), 0);

        this.maincategory = Util.getIntValue(fu.getParameter("maincategory"), 0);
        this.subcategory = Util.getIntValue(fu.getParameter("subcategory"), 0);
        this.seccategory = Util.getIntValue(fu.getParameter("seccategory"), 0);
        
        this.docstatus = fu.getParameter("docstatus");
        this.docEdition = Util.getIntValue(fu.getParameter("docedition"),-1);
        this.docEditionId = Util.getIntValue(fu.getParameter("doceditionid"),-1);
        
        this.docsubject = Util.null2String(fu.getParameter("docsubject"));           
        this.doccreaterid = Util.getIntValue(fu.getParameter("doccreaterid"),0);
        this.docCreaterType = Util.null2String(fu.getParameter("docCreaterType"));           
        
        Calendar today = Calendar.getInstance();
        String formatdate = Util.add0(today.get(Calendar.YEAR), 4) + "-"
                + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-"
                + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);
        String formattime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":"
                + Util.add0(today.get(Calendar.MINUTE), 2) + ":" + Util.add0(today.get(Calendar.SECOND), 2);
        
        this.docPubUserId = this.userid;
        this.docPubUserType = this.usertype;
        this.docPubDate = formatdate;
        this.docPubTime = formattime;
        
        this.docValidUserId = this.userid;
        this.docValidUserType = this.usertype;
        this.docValidDate = formatdate;
        this.docValidTime = formattime;
        
        this.selectedPubMouldId = Util.getIntValue(fu.getParameter("selectedpubmouldid"),-1);
        
        //if(scc.needPubOperation(this.seccategory)&&Util.getIntValue(this.docstatus)==6){
        if(Util.getIntValue(this.docstatus)==6){        
            //生效/正常
            this.docstatus = "2";
            
            
            if(scc.isEditionOpen(this.seccategory)) {//如果版本管理开启
                if(this.docEditionId==-1)
                    this.docEditionId = this.getNextEditionId(rs);
                this.docEdition = dc.getEdition(this.docEditionId)+1;
                
                rs.executeSql(" update docdetail set docstatus = 7,ishistory = 1 where id <> " + this.id + " and docedition > 0 and docedition < " + this.docEdition + " and doceditionid > 0 and doceditionid = " + this.docEditionId);
                
                rs.executeSql(" select id from docdetail where id <> " + this.id + " and docedition < " + this.docEdition + " and doceditionid = " + this.docEditionId + " order by docEdition desc ");
                if(rs.next()){
                    int oldDocId = rs.getInt("id");
                    
                	//关联子文档
                	relateSonDocWithNewDoc(this.id);
                	
                    log.resetParameter();
                    log.setDocId(oldDocId);
                    log.setDocSubject(this.docsubject);
                    log.setOperateType("14");
                    log.setOperateUserid(userid);
                    log.setUsertype(this.usertype);
                    log.setClientAddress(this.clientip);
                    log.setDocCreater(this.doccreaterid);
                    log.setCreatertype(this.docCreaterType);                      
                    log.setDocLogInfo();
                }
            }

            rs.executeSql(
                    " UPDATE DocDetail SET " +
                    " docstatus = " + this.docstatus +
                    ",docEdition = " + this.docEdition +
                    ",docEditionId = " + this.docEditionId +
                    ",selectedpubmouldid = " + this.selectedPubMouldId +
                    ",docpubuserid = " + this.docPubUserId +
                    ",docPubUserType = '" + this.docPubUserType + "'" +                   
                    ",docpubdate = '" + this.docPubDate + "'" +
                    ",docpubtime = '" + this.docPubTime + "'" +
                    ",docvaliduserid = " + this.docValidUserId +
                    ",docValidUserType = '" + this.docValidUserType + "'" +                   
                    ",docvaliddate = '" + this.docValidDate + "'" +
                    ",docvalidtime = '" + this.docValidTime + "'" +
                    " WHERE ID = " + this.id
            );
        
            log.resetParameter();
            log.setDocId(this.id);
            log.setDocSubject(this.docsubject);
            log.setOperateType("13");
            log.setOperateUserid(userid);
            log.setUsertype(this.usertype);
            log.setClientAddress(this.clientip);
            log.setDocCreater(this.doccreaterid);
            log.setCreatertype(this.docCreaterType);              
            log.setDocLogInfo();
                
            if (this.docstatus.equals("2")) {
             //   RecordSet rsforsend = new RecordSet();
             //   rsforsend.executeSql("select shareids from sendtoalltemp where status = 0 and docid=" + this.id);
            //    while (rsforsend.next()) {
             //       String shareids = Util.null2String(rsforsend.getString("shareids"));




                    ThreadForAllForNew sendToAllfornew = new ThreadForAllForNew(this.id+"", "",this.userid+"");
                    sendToAllfornew.start();
               // }
            }
        }
    }
    
    /**
     * 归档文档
     * @param fu FileUpload对象
     * @throws Exception
     */
    public void archiveDoc(FileUpload fu) throws Exception {
        // 归档时进行的操作
        RecordSet rs = new RecordSet();

        this.id = Util.getIntValue(fu.getParameter("id"), 0);

        this.maincategory = Util.getIntValue(fu.getParameter("maincategory"), 0);
        this.subcategory = Util.getIntValue(fu.getParameter("subcategory"), 0);
        this.seccategory = Util.getIntValue(fu.getParameter("seccategory"), 0);
        
        this.docstatus = fu.getParameter("docstatus");
        this.docEdition = Util.getIntValue(fu.getParameter("docedition"),-1);
        this.docEditionId = Util.getIntValue(fu.getParameter("doceditionid"),-1);
        
  
    
        this.doccreaterid = Util.getIntValue(fu.getParameter("doccreaterid"),0);
        this.docCreaterType = Util.null2String(fu.getParameter("docCreaterType"));        
        
        Calendar today = Calendar.getInstance();
        String formatdate = Util.add0(today.get(Calendar.YEAR), 4) + "-"
                + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-"
                + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);
        String formattime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":"
                + Util.add0(today.get(Calendar.MINUTE), 2) + ":" + Util.add0(today.get(Calendar.SECOND), 2);
        
        
        this.docarchiveuserid = this.userid;
        this.docArchiveUserType = this.usertype;
        this.docsubject = fu.getParameter("docsubject");
        this.docno = fu.getParameter("docno");
        this.docarchivedate = formatdate;
        this.docarchivetime = formattime;

        if(Util.getIntValue(this.docstatus)==1||Util.getIntValue(this.docstatus)==2){
            //归档
            this.docstatus = "5";

            //ArchiveDocInfo();

            if(scc.isEditionOpen(this.seccategory)) {//如果版本管理开启
                if(this.docEditionId==-1)
                    this.docEditionId = this.getNextEditionId(rs);
                //this.docEdition = dc.getEdition(this.docEditionId)+1;
                this.docEdition = dc.getEdition(this.docEditionId);
                rs.executeSql(" update docdetail set docstatus = 7,ishistory = 1 where id <> " + this.id + " and docedition > 0 and docedition < " + this.docEdition + " and doceditionid > 0 and doceditionid = " + this.docEditionId);
            }

            rs.executeSql(
                    " UPDATE DocDetail SET " +
                    " docstatus = " + this.docstatus +
                    ",docno = '" + this.docno + "'" +                   
                    ",docEdition = " + this.docEdition +
                    ",docEditionId = " + this.docEditionId +
                    ",docarchiveuserid = " + this.userid +
                    ",docArchiveUserType = '" + this.docArchiveUserType + "'" +                    
                    ",docarchivedate = '" + this.docarchivedate + "'" +
                    ",docarchivetime = '" + this.docarchivetime + "'" +
                    " WHERE ID = " + this.id
            );
            
            
            log.resetParameter();
            log.setDocId(this.id);
            log.setDocSubject(this.docsubject);
            log.setOperateType("7");
            log.setOperateUserid(userid);
            log.setUsertype(this.usertype);
            log.setClientAddress(this.clientip);
            log.setDocCreater(this.doccreaterid);
            log.setCreatertype(this.docCreaterType);             
            log.setDocLogInfo();
            
            
        }
    }

    
    /**
     * 失效文档
     * @param fu FileUpload对象
     * @throws Exception
     */
    public void invalidateDoc(FileUpload fu) throws Exception {
        RecordSet rs = new RecordSet();
        
        this.id = Util.getIntValue(fu.getParameter("id"), 0);

        this.maincategory = Util.getIntValue(fu.getParameter("maincategory"), 0);
        this.subcategory = Util.getIntValue(fu.getParameter("subcategory"), 0);
        this.seccategory = Util.getIntValue(fu.getParameter("seccategory"), 0);
        
        this.docstatus = fu.getParameter("docstatus");
        this.docEdition = Util.getIntValue(fu.getParameter("docedition"),-1);
        this.docEditionId = Util.getIntValue(fu.getParameter("doceditionid"),-1);

        this.docsubject = Util.null2String(fu.getParameter("docsubject"));           
        this.doccreaterid = Util.getIntValue(fu.getParameter("doccreaterid"),0);
        this.docCreaterType = Util.null2String(fu.getParameter("docCreaterType"));
        
        Calendar today = Calendar.getInstance();
        String formatdate = Util.add0(today.get(Calendar.YEAR), 4) + "-"
                + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-"
                + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);
        String formattime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":"
                + Util.add0(today.get(Calendar.MINUTE), 2) + ":" + Util.add0(today.get(Calendar.SECOND), 2);

        this.docInvalUserId = this.userid;
        this.docInvalUserType = this.usertype;
        this.docInvalDate = formatdate;
        this.docInvalTime = formattime;
        
        if(Util.getIntValue(this.docstatus)==1||Util.getIntValue(this.docstatus)==2){
            
            if(scc.needApprove(this.seccategory,2)) {//如果需要审批
                this.docstatus = "3";
                this.approveType = 2;
            } else {//失效
                this.docstatus = "7";
                //this.docInvalUserId = this.userid;
                //this.docInvalDate = formatdate;
                //this.docInvalTime = formattime;
                    
                if(scc.isEditionOpen(this.seccategory)) {//如果版本管理开启
                    if(this.docEditionId==-1)
                        this.docEditionId = this.getNextEditionId(rs);
                    //this.docEdition = dc.getEdition(this.docEditionId)+1;
                    this.docEdition = dc.getEdition(this.docEditionId);
                    rs.executeSql(" update docdetail set docstatus = 7,ishistory = 1 where id <> " + this.id + " and docedition > 0 and docedition < " + this.docEdition + " and doceditionid > 0 and doceditionid = " + this.docEditionId);
                }
            }

            rs.executeSql(
                    " UPDATE DocDetail SET " +
                    " docstatus = " + this.docstatus +
                    ",approvetype = " + this.approveType +
                    ",docEdition = " + this.docEdition +
                    ",docEditionId = " + this.docEditionId +
                    ",docinvaluserid = " + this.docInvalUserId +
                    ",docInvalUserType = '" + this.docInvalUserType + "'" +                  
                    ",docinvaldate = '" + this.docInvalDate + "'" +
                    ",docinvaltime = '" + this.docInvalTime + "'" +
                    " WHERE ID = " + this.id
            );
            
            log.resetParameter();
            log.setDocId(this.id);
            log.setDocSubject(this.docsubject);
            log.setOperateType("14");
            log.setOperateUserid(userid);
            log.setUsertype(this.usertype);
            log.setClientAddress(this.clientip);
            log.setDocCreater(this.doccreaterid);
            log.setCreatertype(this.docCreaterType);             
            log.setDocLogInfo();
            
        }
    }
    
    /**
     * 作废文档
     * @param fu FileUpload对象
     * @throws Exception
     */
    public void cancelDoc(FileUpload fu) throws Exception {
        RecordSet rs = new RecordSet();
        
        this.id = Util.getIntValue(fu.getParameter("id"), 0);

        this.maincategory = Util.getIntValue(fu.getParameter("maincategory"), 0);
        this.subcategory = Util.getIntValue(fu.getParameter("subcategory"), 0);
        this.seccategory = Util.getIntValue(fu.getParameter("seccategory"), 0);
        
        this.docstatus = fu.getParameter("docstatus");
        this.docEdition = Util.getIntValue(fu.getParameter("docedition"),-1);
        this.docEditionId = Util.getIntValue(fu.getParameter("doceditionid"),-1);

        this.docsubject = Util.null2String(fu.getParameter("docsubject"));           
        this.doccreaterid = Util.getIntValue(fu.getParameter("doccreaterid"),0);
        this.docCreaterType = Util.null2String(fu.getParameter("docCreaterType"));
        
        Calendar today = Calendar.getInstance();
        String formatdate = Util.add0(today.get(Calendar.YEAR), 4) + "-"
                + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-"
                + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);
        String formattime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":"
                + Util.add0(today.get(Calendar.MINUTE), 2) + ":" + Util.add0(today.get(Calendar.SECOND), 2);
        
        this.docCancelUserId = this.userid;
        this.docCancelUserType = this.usertype;
        this.docCancelDate = formatdate;
        this.docCancelTime = formattime;
        
        if(Util.getIntValue(this.docstatus)==1||Util.getIntValue(this.docstatus)==2||Util.getIntValue(this.docstatus)==5||Util.getIntValue(this.docstatus)==7){
            //作废
            this.docstatus = "8";

            if(scc.isEditionOpen(this.seccategory)) {//如果版本管理开启
                if(this.docEditionId==-1)
                    this.docEditionId = this.getNextEditionId(rs);
                //this.docEdition = dc.getEdition(this.docEditionId)+1;
                this.docEdition = dc.getEdition(this.docEditionId);
                rs.executeSql(" update docdetail set docstatus = 7,ishistory = 1 where id <> " + this.id + " and docedition > 0 and docedition < " + this.docEdition + " and doceditionid > 0 and doceditionid = " + this.docEditionId);
            }

            rs.executeSql(
                    " UPDATE DocDetail SET " +
                    " docstatus = " + this.docstatus +
                    ",docEdition = " + this.docEdition +
                    ",docEditionId = " + this.docEditionId +
                    ",doccanceluserid = " + this.docCancelUserId +
                    ",docCancelUserType = '" + this.docCancelUserType + "'" +                   
                    ",doccanceldate = '" + this.docCancelDate + "'" +
                    ",doccanceltime = '" + this.docCancelTime + "'" +
                    " WHERE ID = " + this.id
            );
            
            log.resetParameter();
            log.setDocId(this.id);
            log.setDocSubject(this.docsubject);
            log.setOperateType("15");
            log.setOperateUserid(userid);
            log.setUsertype(this.usertype);
            log.setClientAddress(this.clientip);
            log.setDocCreater(this.doccreaterid);
            log.setCreatertype(this.docCreaterType);            
            log.setDocLogInfo();
            
        }
    }

    /**
     * 重新打开文档
     * @param fu FileUpload对象
     * @throws Exception
     */
    public void reopenDoc(FileUpload fu) throws Exception {
        RecordSet rs = new RecordSet();
        
        this.id = Util.getIntValue(fu.getParameter("id"), 0);

        this.maincategory = Util.getIntValue(fu.getParameter("maincategory"), 0);
        this.subcategory = Util.getIntValue(fu.getParameter("subcategory"), 0);
        this.seccategory = Util.getIntValue(fu.getParameter("seccategory"), 0);
        
        this.docstatus = fu.getParameter("docstatus");
        this.docEdition = Util.getIntValue(fu.getParameter("docedition"),-1);
        this.docEditionId = Util.getIntValue(fu.getParameter("doceditionid"),-1);
        
        this.docsubject = Util.null2String(fu.getParameter("docsubject"));        
        this.doccreaterid = Util.getIntValue(fu.getParameter("doccreaterid"),0);
        this.docCreaterType = Util.null2String(fu.getParameter("docCreaterType"));
        
        Calendar today = Calendar.getInstance();
        String formatdate = Util.add0(today.get(Calendar.YEAR), 4) + "-"
                + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-"
                + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);
        String formattime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":"
                + Util.add0(today.get(Calendar.MINUTE), 2) + ":" + Util.add0(today.get(Calendar.SECOND), 2);
        
        this.docReOpenUserId = this.userid;
        this.docReopenUserType=this.usertype;
        this.docReOpenDate = formatdate;
        this.docReOpenTime = formattime;
        this.docInvalUserId = this.userid;
        this.docInvalUserType = this.usertype;
        this.docInvalDate = formatdate;
        this.docInvalTime = formattime;
        
        if(Util.getIntValue(this.docstatus)==5||Util.getIntValue(this.docstatus)==8){
            //重新打开
            if(Util.getIntValue(this.docstatus)==5)
                this.docstatus = "2";
            if(Util.getIntValue(this.docstatus)==8)
                this.docstatus = "7";

            if(scc.isEditionOpen(this.seccategory)) {//如果版本管理开启
                if(this.docEditionId==-1)
                    this.docEditionId = this.getNextEditionId(rs);
                //this.docEdition = dc.getEdition(this.docEditionId)+1;
                this.docEdition = dc.getEdition(this.docEditionId);
                rs.executeSql(" update docdetail set docstatus = 7,ishistory = 1 where id <> " + this.id + " and docedition > 0 and docedition < " + this.docEdition + " and doceditionid > 0 and doceditionid = " + this.docEditionId);
            }

            rs.executeSql(
                    " UPDATE DocDetail SET " +
                    " docstatus = " + this.docstatus +
                    ",docEdition = " + this.docEdition +
                    ",docEditionId = " + this.docEditionId +
                    ",docreopenuserid = " + this.docReOpenUserId +
                    ",docReopenUserType = '" + this.docReopenUserType +"'"+                    
                    ",docreopendate = '" + this.docReOpenDate + "'" +
                    ",docreopentime = '" + this.docReOpenTime + "'" +
                    ",docinvaluserid = " + this.docInvalUserId +
                    ",docInvalUserType = '" + this.docInvalUserType + "'" +                  
                    ",docinvaldate = '" + this.docInvalDate + "'" +
                    ",docinvaltime = '" + this.docInvalTime + "'" +
                    " WHERE ID = " + this.id
            );
            
            log.resetParameter();
            log.setDocId(this.id);
            log.setDocSubject(this.docsubject);
            log.setOperateType("6");
            log.setOperateUserid(userid);
            log.setUsertype(this.usertype);           
            log.setClientAddress(this.clientip);
            log.setDocCreater(this.doccreaterid);
            log.setCreatertype(this.docCreaterType);
            log.setDocLogInfo();
             
        }
    }   
	//关联子文档
    public void relateSonDocWithNewDoc(int newDocId){
    	RecordSet rs1 = new RecordSet();
    	RecordSet rs2 = new RecordSet();
    	
    	rs1.executeSql(" select doceditionid from docdetail where id = " + newDocId);
    	if(rs1.next()){
    		String doceditionid = Util.null2String(rs1.getString("doceditionid"));
    		String docids = "";
    		if("-1".equals(doceditionid)||"".equals(doceditionid) ){  //不应该查询所有非版本管理的文档
    			return;
    		}
    		rs2.executeSql(" select id from docdetail where doceditionid = " + doceditionid);
    		while(rs2.next()){
    			docids += ",";
    			docids += Util.null2String(rs2.getString("id"));
    		}
    		if(docids.startsWith(",")) docids=docids.substring(1);
    		if(docids!=null&&!"".equals(docids))
    		rs2.executeSql("update docdetail set maindoc = " + newDocId + " where maindoc in (" + docids + ")");
    	}
    }
    public String getNewDocids(String docids){
    	String sNewDocids="";
    	ArrayList lstDocid=Util.TokenizerString(docids, ",");
    	for(int i=0;i<lstDocid.size();i++) {
    		String docid=(String)lstDocid.get(i);
    		String newDocid=this.getNewDocid(docid);
    		sNewDocids+=newDocid+",";    		
    	}
    	if(!"".equals(sNewDocids)) sNewDocids=sNewDocids.substring(0,sNewDocids.length()-1);
    	return sNewDocids;
    }
    
    public String getNewDocid(String docid){
    	String sNewDocid="";    	
    	String sDoceditionid="-1";
    	if("".equals(docid)) return "";
    	RecordSet rs= new RecordSet();
    	rs.executeSql("select doceditionid from docdetail where id="+docid);
    	if(rs.next()) sDoceditionid=Util.null2String(rs.getString("doceditionid"));
        if("-1".equals(sDoceditionid) || "".equals(sDoceditionid)) return docid;
        rs.executeSql("select id from docdetail where docedition=(select max(docedition) from docdetail where doceditionid="+sDoceditionid+") " +
        		"and doceditionid="+sDoceditionid);
        
        if(rs.next()) sNewDocid=Util.null2String(rs.getString("id"));
        
        if("".equals(sNewDocid)) sNewDocid=docid;        
    	return sNewDocid;    	
    }
    
    
    /**
     * 新建文档
     * @param request request对象
     * @param opera 操作类型
     * @param imgfileidList 附件列表集合
     * @throws Exception
     */
    public void UploadFileToDoc(HttpServletRequest request,String fileid) throws Exception {
    	
        RecordSet rs = new RecordSet();
        FileUpload fu = new FileUpload(request);   
        
        this.seccategory = Util.getIntValue(fu.getParameter("seccategory"), 0);
        this.subcategory=Util.getIntValue(scc.getSubCategoryid(""+this.seccategory));
        this.maincategory=Util.getIntValue(subc.getMainCategoryid(""+this.subcategory));
        
        String filename="";
        
        this.id=this.getNextDocId(rs);
        this.docextendname = "html";  
        
        
        rs.executeSql("select imagefilename from imagefile where imagefileid="+fileid);
        if(rs.next()){
        	filename=rs.getString(1);
        }
        String filename_bak=filename;
        if(filename.indexOf(".")>0)
			filename_bak=filename.substring(0,filename.lastIndexOf("."));
       
       rs.execute("select * from DocSecCategory where id="+seccategory+" and norepeatedname=1");
       if(rs.next())
       {
    	   rs.execute("select * from DocDetail where seccategory="+seccategory+" and docsubject='"+filename_bak+"'");
    	   if(rs.next())
    	   {
    		   String msg_str = ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10003405,weaver.general.ThreadVarLanguage.getLang())+"";
    		   HttpSession session =request.getSession();
    		   session.setAttribute("msg_str", msg_str);
    		   return;
    	   }
       }

        // add by wjy for add custom data
        addCustomData(fu, this.id);

        // 开始进行存储附件的操作
        imgManger.resetParameter();
        imgManger.setDocid(this.id);
        imgManger.setImagefileid(Util.getIntValue(fileid, 0));
        imgManger.setImagefilename(filename);
        imgManger.setIsextfile("1");
        imgManger.setVersionDetail("128095");
        imgManger.setOperateuserid(userid);
        String ext = getFileExt(filename);
        if (ext.equalsIgnoreCase("doc")) {
            imgManger.setDocfiletype("3");
        } else if (ext.equalsIgnoreCase("xls")) {
            imgManger.setDocfiletype("4");
        } else if (ext.equalsIgnoreCase("ppt")) {
            imgManger.setDocfiletype("5");
        } else if (ext.equalsIgnoreCase("wps")) {
            imgManger.setDocfiletype("6");
        } else if (ext.equalsIgnoreCase("docx")) {
            imgManger.setDocfiletype("7");
        } else if (ext.equalsIgnoreCase("xlsx")) {
            imgManger.setDocfiletype("8");
        } else if (ext.equalsIgnoreCase("pptx")) {
            imgManger.setDocfiletype("9");
        } else if (ext.equalsIgnoreCase("et")) {
            imgManger.setDocfiletype("10");
        } else {
            imgManger.setDocfiletype("2");
        }
        imgManger.AddDocImageInfo();
        
        // 存储文档的内容
        this.doccontent = Util.fromBaseEncoding(fu.getParameter("doccontent"), languageid);
        this.doccontent =Util.htmlFilter4UTF8(this.doccontent );

        // 下面的操作可以得到此知识文档的相关资料
        Calendar today = Calendar.getInstance();
        String formatdate = Util.add0(today.get(Calendar.YEAR), 4) + "-"
                + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-"
                + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);
        String formattime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":"
                + Util.add0(today.get(Calendar.MINUTE), 2) + ":" + Util.add0(today.get(Calendar.SECOND), 2);

        this.seccategory = Util.getIntValue(fu.getParameter("seccategory"), 0);
        this.subcategory=Util.getIntValue(scc.getSubCategoryid(""+this.seccategory));
        this.maincategory=Util.getIntValue(subc.getMainCategoryid(""+this.subcategory));
        
        this.doclangurage = Util.getIntValue(fu.getParameter("doclangurage"), 0);
        this.docreplyable = fu.getParameter("docreplyable");
        this.isreply = Util.null2String(fu.getParameter("isreply"));
        this.replydocid = Util.getIntValue(fu.getParameter("replydocid"), 0);
        this.ownerid = Util.getIntValue(fu.getParameter("ownerid"), 0);
        this.ownerType = this.usertype;    
        
        this.doclangurage = Util.getIntValue(fu.getParameter("doclangurage"), 0);
        
        int tempPos=filename.lastIndexOf(".");
        if(tempPos==-1) this.docsubject = filename;
        else  this.docsubject = filename.substring(0, tempPos);

        this.docpublishtype = fu.getParameter("docpublishtype");
        if (docpublishtype.equals("2")) {
            //String docmain = fu.getParameter("docmain");
        	String docmain = Util.toHtml2(Util.encodeAnd(Util.null2String(fu.getParameter("docmain"))));        	
            this.doccontent = docmain + "!@#$%^&*" + this.doccontent;
        }

        this.itemid = Util.getIntValue(fu.getParameter("itemid"), 0);
        this.itemmaincategoryid = Util.getIntValue(fu.getParameter("itemmaincategoryid"), 0);
        this.hrmresid = Util.getIntValue(fu.getParameter("hrmresid"), 0);
        this.assetid = Util.getIntValue(fu.getParameter("assetid"), 0);
        this.crmid = Util.getIntValue(fu.getParameter("crmid"), 0);
        this.projectid = Util.getIntValue(fu.getParameter("projectid"), 0);
        this.financeid = Util.getIntValue(fu.getParameter("financeid"), 0);
        this.doccreaterid = this.userid;
        this.docCreaterType=this.usertype;
        // TD1715 新建或者编辑文档时，更改文档的所有者，促使文档所在的部门被清除 DP
        this.docdepartmentid = Util.getIntValue(hrc.getDepartmentID("" + ownerid));
        // this.docdepartmentid =
        // Util.getIntValue(fu.getParameter("docdepartmentid"), 0);
        this.doccreatedate = formatdate;
        this.doccreatetime = formattime;
        this.doclastmoduserid = this.userid;
        this.docLastModUserType=this.usertype;
        this.doclastmoddate = formatdate;
        this.doclastmodtime = formattime;
        this.docapproveuserid = 0;
        this.docApproveUserType = "";
        this.docapprovedate = "";
        this.docapprovetime = "";
        this.docarchiveuserid = 0;
        this.docArchiveUserType = "";
        this.docarchivedate = "";
        this.docarchivetime = "";
        this.newsid = Util.getIntValue(fu.getParameter("newsid"), 0);

        rs = new RecordSet();
        SysRemindWorkflow srw = new SysRemindWorkflow();
        String sql = "";
        if (replydocid != 0) {
            sql = "select id,canremind,docsubject,doccreaterid from DocDetail where id=" + replydocid;
            //System.out.println("sql = " + sql);
            String canRemind = "";
            rs.executeSql(sql);
            if (rs.next()) {
                canRemind = rs.getString("canremind");
                if (canRemind.equals("2")) {
                    srw.setSysRemindInfo("回复提醒:" + rs.getString("docsubject"), this.id, 0, 0, 0, this.userid,
                            rs.getString("doccreaterid") + "", "");
                }
            }
        }

        if (Util.null2String(fu.getParameter("parentids")).equals("")) {
            this.parentids = this.id + "";
        } else {
            this.parentids = Util.null2String(fu.getParameter("parentids")) + "," + this.id;
        }

        this.keyword = Util.null2String(fu.getParameter("keyword"));
        /* 文档的关键字 */

        int docid = this.id;

        this.accessorycount = 1;

        if (isreply.equals("1")) {
            AddReplayDocCount(rs); // 修改回复记录条数
        }

        /* 回复文档总数 */
        this.replaydoccount = 0;
        /* 创建的用户类型 1: 内部 2: 外部 */
        //this.usertype = Util.null2String(fu.getParameter("usertype"));
        this.topage = Util.null2String(fu.getParameter("topage"));

        this.contractman = Util.null2String(fu.getParameter("contractman"));
        this.contractstartdate = Util.null2String(fu.getParameter("contractstartdate"));
        this.contractenddate = Util.null2String(fu.getParameter("contractenddate"));
        this.docmodule = Util.null2String(fu.getParameter("docmodule"));
        this.proenddate = Util.null2String(fu.getParameter("proenddate"));
        this.typeid = Util.getIntValue(fu.getParameter("typeid"), 0);
        this.urlfrom = Util.null2String(fu.getParameter("urlfrom"));
        this.canCopy = "" + Util.getIntValue(fu.getParameter("cancopy"), 1);
        this.canRemind = "" + Util.getIntValue(fu.getParameter("canremind"), 1);

        // get catagory's orderable
        this.orderable = "" + scc.getSecOrderable(this.seccategory);
        
        this.docEdition = Util.getIntValue(fu.getParameter("docedition"),-1);
        this.docEditionId = Util.getIntValue(fu.getParameter("doceditionid"),-1);
        
        if(scc.isEditionOpen(this.seccategory)) {//如果版本管理开启
            if(this.docEditionId == -1){// 如果不存在历史版本
                this.docEditionId = this.getNextEditionId(rs);
            } else {
                // TODO 否则，通过版本ID找到同文档的版本
                //新建文档不存在以前有版本
            }
            this.docEdition = dc.getEdition(this.docEditionId)+1;
        }
        
        this.mainDoc = Util.getIntValue(Util.null2String(fu.getParameter("maindoc")),-1);
        if(this.mainDoc==-1) this.mainDoc = this.id;
        
        // added by wdl
        this.docCode = Util.null2String(fu.getParameter("doccode"));
        if(this.docCode.equals("")){
            DocCoder dc = new DocCoder(); 
            if(this.mainDoc == this.id){
            	this.docCode = dc.getDocCoder(""+this.seccategory);
            }else{
            	this.docCode = dc.getSecDocCoder(""+mainDoc,""+this.seccategory);
            }
        }
        
        this.readOpterCanPrint = Util.getIntValue(fu.getParameter("readoptercanprint"), 0);
        
        this.invalidationDate = Util.null2String(fu.getParameter("invalidationdate"));
		this.dummycata = Util.null2String(fu.getParameter("dummycata"));
        
        if(scc.isNoRepeatedName(this.seccategory)){
            // TODO
            
        }
        
        this.docstatus = "1";
        
        // 如果在目录上设置了 创建者对此目录下的文档无权限查看则此文档被直接置为正常 TD4111 TD4112 begin
        RecordSet rsCreater = new RecordSet();
        int pcreater = 3;
        String strCreaterSql = "select pcreater from secCreaterDocPope where secid=" + this.seccategory;

        rsCreater.executeSql(strCreaterSql);
        if (rsCreater.next()) {
            pcreater = Util.getIntValue(rsCreater.getString("pcreater"), 0);
        }
       
        if (!contractman.equals("")) {
            this.docstatus = "1";
            docCreaterType="";
        }
        
        this.secretLevel = Util.getIntValue(fu.getParameter("secretLevel"),DEFAILT_SECRET_LEVEL);
        this.secretValidity = Util.null2s(fu.getParameter("secretValidity"),"");

        this.replyremind =  Util.getIntValue(fu.getParameter("replyremind"),0);

        AddDocInfo();
        AddShareInfo();
        
        DocViewer DocViewer = new DocViewer();
        DocViewer.setDocShareByDoc("" + this.id);

		DocComInfo docComInfo =new DocComInfo();
        RecordSet rsforsend = new RecordSet();
        SendToAllForNew  sendToAllForNew = new SendToAllForNew();
        String sendToAll = sendToAllForNew.checkeSendingRightForDocid(  this.id+"");
        int docId = this.id;
        //设置推送提醒 start
        String docstatus = docComInfo.getDocStatus(this.id+"");
        if("1".equals(sendToAll)){
            if("3".equals(docstatus)||"6".equals(docstatus)||"9".equals(docstatus)){
                if("-1".equals(sendToAllForNew.checkIsExist(docId+""))){
                    rsforsend.executeSql("insert into sendtoalltemp (docid,shareids,status) values ("+docId+",'',0)");
                }
            }else if("1".equals(docstatus) || "2".equals(docstatus)){
                User user = new User(this.userid);
                ThreadForAllForNew sendToAllfornew = new ThreadForAllForNew(docId+"","",user);
                sendToAllfornew.start();
            }

        }
        //设置推送提醒 end
    }

    /**
     * 截取不大于指定字节长度的字符串
     * @param initString 初始字符串
     * @param byteLength 指定字节长度
     * @return String 不大于指定字节长度的字符串
     */  
  	private static String interceptString(String initString,int byteLength) {
  		try{
  			
  		    String returnString="";
  			int counterOfDoubleByte = 0;
  			byte[] b = initString.getBytes("UTF-8");
  			  if(b.length <= byteLength)
  			    return initString;
  			  for(int i = 0; i < byteLength; i++){
  			    if(b[i] < 0)
  			      counterOfDoubleByte++;
  			  }

  			  if(counterOfDoubleByte % 2 == 0){
  				returnString=new String(b, 0, byteLength, "UTF-8");
  			  }else{
  				returnString=new String(b, 0, byteLength - 1, "UTF-8");
  			  }
  			  
  			  List noInterceptStringList =new ArrayList();
  			  noInterceptStringList.add("&lt;");
  			  noInterceptStringList.add("&gt;");  			  
  			  noInterceptStringList.add("&quot;");
  			  noInterceptStringList.add("<br>");
  			  
  			  List partList=new ArrayList();
  			  List allList=new ArrayList();
  			  
  			  String noInterceptString=null;
  			  for(int i=0;i<noInterceptStringList.size();i++){
  				  noInterceptString = Util.null2String((String)noInterceptStringList.get(i));
  				  for(int j=1;j<noInterceptString.length();j++){
  					  partList.add(noInterceptString.substring(0,j));
  					  allList.add(noInterceptString);					  
  				  }
  			  }
  		  			  
  			  String partString=null;
  			  String allString=null;
  			  int lastIndex=0;
  			
  			  for(int i=0;i<partList.size();i++){
  				  partString = (String)partList.get(i);
  				  allString  = (String)allList.get(i); 
  				  
  	  			  if(returnString.endsWith(partString)){
  	  				  lastIndex = returnString.lastIndexOf(partString);
  	  				  if(lastIndex==initString.indexOf(allString,lastIndex)){
  	  					  returnString=initString.substring(0,lastIndex);
  	  					  break;
  	  				  }
  	  			  } 				  
  			  }  			
  			  
  			  return returnString;
  			
  		}catch(Exception ex){
  			return "";
  		}
  	}

	public String[] getCustomDataIdMapping() {
		return customDataIdMapping;
	}

	public void setCustomDataIdMapping(String[] customDataIdMapping) {
		this.customDataIdMapping = customDataIdMapping;
	}
	
    /**
	 * 获得新的下拉框的值
	 * 
	 * @param workflowFieldShowName 表单下拉框显示值
	 * @param workflowFieldValue 表单下拉框字段值
	 * @param fieldId 文档属性页字段id
	 * 
	 * @return String  新的下拉框的值
	 */		
	private  String getNewSelectValue(String workflowFieldShowName, String workflowFieldValue,int fieldId) {
		try{
			String newSelectValue="";
			workflowFieldShowName=Util.null2String(workflowFieldShowName);
			RecordSet rsTwo=new RecordSet();
			rsTwo.executeSql("select selectValue from cus_selectitem where fieldId="+fieldId+" and selectName='"+Util.toHtml100(workflowFieldShowName)+"'");
			if(rsTwo.next()){
				newSelectValue=Util.null2String(rsTwo.getString("selectValue"));
			}
			if(newSelectValue.equals("")){
				newSelectValue=workflowFieldValue;
			}
			return newSelectValue;
		}catch(Exception ex){
			return workflowFieldValue;
		}
	}
	/**
	 * 获取第一个查询期间
	 * @return
	 */
	public int getDateDuringForFirst()
	{
		BaseBean baseBean = new BaseBean();
		int date2during = 0;
		String date2durings = "";
		try
		{
			date2durings = Util.null2String(baseBean.getPropValue("docdateduring", "date2during"));
		}
		catch(Exception e)
		{}
		String[] date2duringTokens = Util.TokenizerString2(date2durings,",");
		if(date2duringTokens.length>0)
		{
			date2during = Util.getIntValue(date2duringTokens[0],0);
		}
		if(date2during<0||date2during>36)
		{
			date2during = 0;
		}
		return date2during;
	}
	
	/**
	 * 获取门户文档中心查询间期
	 * @return
	 */
	public int getDateDuringForHp(){
		BaseBean baseBean = new BaseBean();
		int date2during = 0;
		String date2durings = "";
		try
		{
			date2durings = Util.null2String(baseBean.getPropValue("docdateduring", "date2duringforhp"));
		}
		catch(Exception e)
		{}
		
		date2during = Util.getIntValue(date2durings,0);
		
		if(date2during<0||date2during>36)
		{
			date2during = 0;
		}
		return date2during;
	}
	/**
	 * 返回文档期间查询sql
	 * @param date2during
	 * @return
	 */
	public String getDateDuringSql(int date2during)
	{
		String strResult = "";
		Calendar now = Calendar.getInstance();
        String today=Util.add0(now.get(Calendar.YEAR), 4) +"-"+
        	Util.add0(now.get(Calendar.MONTH) + 1, 2) +"-"+
                Util.add0(now.get(Calendar.DAY_OF_MONTH), 2) ;
        int year=now.get(Calendar.YEAR);
        int month=now.get(Calendar.MONTH);
        int day=now.get(Calendar.DAY_OF_MONTH);
		if(date2during>0&&date2during<37)
		{
    		Calendar tempday = Calendar.getInstance();
    		tempday.clear();
    		tempday.set(year,month,day-30*date2during);
    		
    		String lastday=Util.add0(tempday.get(Calendar.YEAR), 4) +"-"+Util.add0(tempday.get(Calendar.MONTH) + 1, 2) +"-"+Util.add0(tempday.get(Calendar.DAY_OF_MONTH), 2) ;
    	    strResult+=" and doclastmoddate>'"+lastday+"' ";
    	}
		return strResult;
	}
	
    /**
	 * 更新文档图片对应关系
	 * 
	 * @param docid 文档id
	 * @param doccontent 文档内容
	 * 
	 */	
	private void updateDocImageFileOfPic(int docid,String doccontent){
		List existsimagefileidlist=new ArrayList();
		List htmlimagefileidlist=new ArrayList();
		List deletedimagefileidlist=new ArrayList();
		int imagefileid=0;
		RecordSet rsTwo=new RecordSet();
		rsTwo.executeSql("select imagefileid from docimagefile where docid="+docid+" and docfiletype='1'");
		while(rsTwo.next()){
			imagefileid=Util.getIntValue(rsTwo.getString("imagefileid"),-1);
			existsimagefileidlist.add(""+imagefileid);
		}
		List newimagefileidlist=new ArrayList();		
        int tmppos = doccontent.indexOf("/weaver/weaver.file.FileDownload?fileid=");
        while (tmppos != -1) {
        	int imagefileidbeginpos=tmppos+"/weaver/weaver.file.FileDownload?fileid=".length();       	
        	int imagefileidendpos1=doccontent.indexOf("\"",tmppos);
        	int imagefileidendpos2=doccontent.indexOf("&",tmppos);
        	//int imagefileidendpos=imagefileidendpos1<imagefileidendpos2?imagefileidendpos1:imagefileidendpos2;
        	int imagefileidendpos=imagefileidendpos1;
        	if(imagefileidendpos1>imagefileidendpos2&&imagefileidendpos2>tmppos){
        		imagefileidendpos=imagefileidendpos2;
        	}
        	
        	if(imagefileidendpos>imagefileidbeginpos){
            	imagefileid=Util.getIntValue(doccontent.substring(imagefileidbeginpos,imagefileidendpos));
				if(imagefileid>0){
            		htmlimagefileidlist.add(""+imagefileid);
            	}
                if(existsimagefileidlist.indexOf(""+imagefileid)==-1){
                	newimagefileidlist.add(""+imagefileid);
                }
        	}
        	tmppos = doccontent.indexOf("/weaver/weaver.file.FileDownload?fileid=", tmppos + 1);
        } 
        for(int i=0;i<newimagefileidlist.size();i++){
        	imagefileid=Util.getIntValue((String)newimagefileidlist.get(i));
        	
        	rsTwo.executeSql("select imagefilename,imagefilewidth,imagefileheight,imagefielsize from docimagefile where imagefileid="+imagefileid+" and docfiletype='1'");
        	if(rsTwo.next()){
        		String imagefilename=Util.null2String(rsTwo.getString("imagefilename"));       		
        		int imagefilewidth=Util.getIntValue(rsTwo.getString("imagefilewidth"),-1);
        		int imagefileheight=Util.getIntValue(rsTwo.getString("imagefileheight"),-1);
        		int imagefielsize=Util.getIntValue(rsTwo.getString("imagefielsize"),-1);
        		
            	rsTwo.executeProc("imagefile_AddByDoc", ""+imagefileid);

                imgManger.resetParameter();
                imgManger.setDocid(docid);
                imgManger.setImagefileid(imagefileid);
                imgManger.setImagefilename(imagefilename);
                imgManger.setDocfiletype("1");

                imgManger.setImagefielsize(imagefielsize);
                imgManger.setimagefilewidth(imagefilewidth);
                imgManger.setImagefileheight(imagefileheight);
                
                imgManger.AddDocImageInfo();              	
        	}else{
            	rsTwo.executeSql("select a.imagefilename,a.fileSize,b.docfiletype from ImageFile a,ImageFileTempPic b where a.imageFileId=b.imageFileId and  a.imagefileid ="+imagefileid);
            	if(rsTwo.next()){
					String imagefilename=Util.null2String(rsTwo.getString("imagefilename"));       		
	        		int imagefilewidth=Util.getIntValue("",-1);
	        		int imagefileheight=Util.getIntValue("",-1);
	        		int imagefielsize=Util.getIntValue(rsTwo.getString("fileSize"),-1);
					String docfiletype=Util.null2String(rsTwo.getString("docfiletype"));
					if(docfiletype.trim().equals("")){
						docfiletype="1";
					}

	                imgManger.resetParameter();
	                imgManger.setDocid(docid);
	                imgManger.setImagefileid(imagefileid);
	                imgManger.setImagefilename(imagefilename);
	                imgManger.setDocfiletype(docfiletype);

	                imgManger.setImagefielsize(imagefielsize);
	                imgManger.setimagefilewidth(imagefilewidth);
	                imgManger.setImagefileheight(imagefileheight);
	                
	                imgManger.AddDocImageInfo(); 
	                
	            	rsTwo.executeSql("delete from ImageFileTempPic where imageFileId="+imagefileid);
            	}
			}
        }
		for(int i=0;i<existsimagefileidlist.size();i++){
        	imagefileid=Util.getIntValue((String)existsimagefileidlist.get(i));
            if(htmlimagefileidlist.indexOf(""+imagefileid)==-1){
            	deletedimagefileidlist.add(""+imagefileid);
            }        	
        }
        for(int i=0;i<deletedimagefileidlist.size();i++){
        	imagefileid=Util.getIntValue((String)deletedimagefileidlist.get(i));
            if(imagefileid>0){
                imgManger.resetParameter();
                imgManger.setImagefileid(imagefileid);
                imgManger.setDocid(docid);
                imgManger.DeleteSingleDocImageInfo();            	
            }
        }  
	}
	
	/**
	 * 修正创建或者编辑文档时，文档内容中的图片和文档对应关系
	 * @param docid
	 * @param docContent
	 * 备注：该方法建议停用
	 */
	public void correctDocImageFileByDocContent(int docid,String docContent){
		ArrayList list=Util.matchAll(docContent,"/weaver/weaver.file.FileDownload\\?fileid=([0-9]+)",1,1);
		RecordSet rsTwo= new RecordSet();
		RecordSet rs2= new RecordSet();
		for(int i=0;i<list.size();i++){
			String fileid =  (String)list.get(i);
			if(!isExists(docid,fileid)){
				rsTwo.execute("select * from imagefile where imagefileid = '"+fileid+"'");
				if(rsTwo.next()){
					String imagefilename=Util.null2String(rsTwo.getString("imagefilename"));       		
	        		int imagefilewidth=Util.getIntValue("",-1);
	        		int imagefileheight=Util.getIntValue("",-1);
	        		int imagefielsize=Util.getIntValue(rsTwo.getString("fileSize"),-1);
	        		
	            	rsTwo.executeProc("imagefile_AddByDoc", ""+fileid);

	                imgManger.resetParameter();
	                imgManger.setDocid(docid);
	                imgManger.setImagefileid(fileid);
	                imgManger.setImagefilename(imagefilename);
	                imgManger.setDocfiletype("1");

	                imgManger.setImagefielsize(imagefielsize);
	                imgManger.setimagefilewidth(imagefilewidth);
	                imgManger.setImagefileheight(imagefileheight);
	                
	                imgManger.AddDocImageInfo();  
				}
			}
		}
		
	}
	
	/**
	 * 判断文档内容中图片是否已经存在
	 * @param docid
	 * @param fileid
	 * @return
	 */
	private boolean isExists(int docid,String fileid){
		boolean flag = false;
		RecordSet rsTwo= new RecordSet();
		rsTwo.execute("select count(*) as count from docimagefile where docid='"+docid+"' and imagefileid='"+fileid+"'");
		if(rsTwo.next()){
			if(rsTwo.getInt("count")>0){
				flag = true;
			}
		}
		
		return flag;
	}
	
    /**
	 * 更新文档图片对应关系
	 * 
	 * @param docid 文档id
	 * @param deleteaccessory 被删除的附件id
	 * @return String  被删除的所有版本的附件id
	 */	
	private String getAllDeleteaccessory(int docid,String deleteaccessory){
		
		if(deleteaccessory==null||deleteaccessory.trim().equals("")){
			return "";
		}
		
		String returndeleteaccessory=deleteaccessory;
		int imagefileid=0;
		RecordSet rsTwo=new RecordSet();
		rsTwo.executeSql("select imagefileid from docimagefile a where a.docid="+docid+" and exists(select * from docimagefile b where b.docid="+docid+" and b.imagefileid in ("+deleteaccessory+") and b.id=a.id)");
		while(rsTwo.next()){
			imagefileid=Util.getIntValue(rsTwo.getString("imagefileid"),-1);
			if(imagefileid<=0){
				continue;
			}
			if((","+returndeleteaccessory+",").indexOf(","+imagefileid+",")==-1){
				returndeleteaccessory=returndeleteaccessory+","+imagefileid;
			}
		}
		return returndeleteaccessory;
	}	
	public static int getReplyCount125(String docid){
        RecordSet rs125 = new RecordSet();
        rs125.executeSql("select replaydoccount from DocDetail where id="+docid);
        if(rs125.next()) return rs125.getInt(1);
        return 0;
  }
	public String getSource() {
		return source;
	}

	public void setSource(String source) {
		this.source = source;
	}
}
